Line plots with Python and TikZ
python3 example.py
pdflatex example.tex
Installation¶
Using a virtual environment:
python3 m venv venv
source venv/bin/activate
python3 m pip install upgrade pip setuptools wheel
Either from GitHub:
python3 m pip install git+https://github.com/janberges/StoryLines
Or from PyPI:
python3 m pip install storylines
Objects and functions¶

class
storylines.
Plot
(width=8.0, height=6.0, margin=None, xyaxes=True, style=None, **more)¶ Plot object.
 Parameters
 widthfloat, default 8.0
Figure width in cm. A negative value is interpreted as the inner width (without left and right margins). If zero, the xaxis scale is set equal to the yaxis scale and the width is inferred from the height.
 heightfloat, default 6.0
Figure height in cm. A negative value is interpreted as the innter height (without bottom and top margins). If zero, the yaxis scale is set equal to the xaxis scale and the height is inferred from the width.
 marginfloat, default None
Default margin in cm. If
None
, margins are set automatically. This is not always the best option. xyaxesbool, default True
Draw x and y axes?
 stylestr, default None
Predefined style. Possible values are
'Nature'
and'APS'
. This changes some of the below default values. **more
Global TikZ options.
Notes
In all textual attributes and parameters, numbers in angle brackets are interpreted as values in y data units, e.g.,
line_width='<0.1>'
. For the parameters line_width and mark_size this is also the case if an integer or float is passed instead of a string. Attributes
 leftfloat, default margin
Left margin in cm.
 rightfloat, default margin
Right margin in cm.
 bottomfloat, default margin
Bottom margin in cm.
 topfloat, default margin
Top margin in cm.
 xlabel, ylabel, zlabelstr, default None
Axis labels.
 xticks, yticks, ztickslist, default None
List of ticks, e.g.,
[0, (0.5, '$\frac12$'), 1]
. xspacing, yspacing, zspacingfloat, default 1.0
Approximate tick spacing in cm.
 xstep, ystep, zstepfloat, default None
Exact tick increment.
 xmin, ymin, zminfloat, default None
Lower axis limit.
 xmax, ymax, zmaxfloat, default None
Upper axis limit.
 xpadding, ypadding, zpaddingfloat, default 0.0
Padding between data and axes in data units.
 xformat, yformat, zformatfunction
Tick formatter. Takes tick position as argument.
 lowerstr, default ‘blue’
Lower color of colorbar.
 upperstr, default ‘red’
Upper color of colorbar.
 titlestr, default None
Plot title.
 labelstr, default None
Subfigure label, e.g.,
'(a)'
. labelsizeint, default None
Different font size for subfigure label in pt.
 labelformatfunction, default None
Formatter for subfigure label. Takes label as argument.
 lalistr, default ‘center’
Alignment of legend entries.
 lblsstr, default ‘baselineskip’
Line height of legend entries.
 lboxbool, default False
Draw box around legend?
 lcolint, default 1
Number of columns in legend.
 llenstr, default ‘4mm’
Length of example lines next to labels.
 loptstr, default ‘below left’
Legend options, e.g., for orientation.
 lposstr, default ‘lt’
Legend position, a combination of
lcrbmtLCRBMT
. lputbool, default True
Draw legend?
 lrowint, default 0
Number of rows in legend.
 lsepstr, default None
Space between legend title and entries, e.g.,
'6pt'
. ltopstr, default None
Legend title.
 lwidfloat, default 4.0
Width of legend columns in cm.
 tickstr, default 0.07
Length of tick marks in cm.
 gapfloat, default 0.0
Gap between plot area and colorbar in cm.
 tipfloat, default 0.1
Overlap of axis tips in cm.
 xaxisbool, default xyaxes
Draw x axis?
 yaxisbool, default xyaxes
Draw y axis?
 framebool, default xyaxes
Draw frame around plot area?
 colorbarbool, default True
Draw possible colorbar?
 outlinebool, default False
Draw dashed figure outline?
 backgroundstr, default None
Path to background image.
 preamblestr, default ‘’
Definitions for standalone figures.
 inputencstr, default None
Text endocing, e.g.,
'utf8'
. fontencstr
Font endocing. The default is``’T1’`` if font is specified,
None
otherwise. fontstr, default None
Prefined font selection. Imitates wellknown fonts. Possible values are
'Gill Sans'
,'Helvetica'
,'Iwona'
,'Latin Modern'
, and'Times'
. fontsizeint, default 10
Font size for standalone figures in pt.
 flexiblebool, default False
Scale plot to fill whole line?
 lineslist
List of all line objects.
 optionsdict
Global TikZ options.

axes
(**options)¶ Draw axes at current position.

clear
()¶ Remove all lines from plot.

code
(data, **options)¶ Insert literal TikZ code.
 Parameters
 datastr
TikZ code. Positions and distances in data coordinates and units can be specified using angle brackets, e.g.,
(<x=1>, <y=2>)
or+(<dx=1>, <dy=2)
. **options
Options passed to line.

compline
(x, y, weights, colors, threshold=0.0, **options)¶ Represent points of multiple weights as composite fatband.
 Parameters
 x, ylist of float
Coordinates of line vertices.
 weightslist of tuple of float, list of float, or float
Weights of vertices. The corresponding linewidth is always measured perpendicular to the direction of the line; This ensures that lines of the same weight have the same thickness regardless of direction.
 colorslist of str
Colors of different components. Any objects whose representations as a string are valid LaTeX colors can be used.
 thresholdfloat
Minimum displayed weight.
 **options
Further line options.

fatband
(x, y, weights, shifts=None, **options)¶ Draw fatband.
 Parameters
 x, ylist
Vertices of linear spline.
 weightslist of float
Weights of x and y.
 shiftslist of float
Displacements in weight direction.
 **options
Options passed to line function.

line
(x=[], y=[], z=None, axes=False, code=None, cut=False, frame=False, join=None, jump=0, label=None, miter=False, nib=None, omit=True, protrusion=0, sgn=1, shifts=None, shortcut=0, shortcut_rel=0.5, thickness=1, weights=None, xref=None, yref=None, zindex=None, **options)¶ Add line/curve.
 Parameters
 x, ylist or float
Coordinates of data points.
 zfloat, default None
z value for entire line, represented by color.
 axesbool, default False
Draw axes at current z index? By default, the axes are drawn on top of all data.
 codestr, default None
Literal TikZ code to be inserted at current position.
 cutbool, default False
Cut off line segments beyond plotting range?
 framebool, default False
Draw frame at current z index? By default, the frame is drawn just below the axes.
 joinbool, default None
Join cutup line segments along edge of plotting range? By default, this is
True
if anyfill
is specified,False
otherwise. jumpfloat, default 0
Shortest distance between consecutive data points that is considered as a discontinuity.
 labelstr, default None
Label for legend entry.
 miterbool, default False
Draw fatbands using miter_butt function? If
False
, the fatband function is used. nibfloat, default None
Angle of broad pen nib. If
None
, the nib is held perpendicular to the direction of the current line segment. omitbool, default True
Remove irrelevant vertices of linear spline?
 protrusionfloat, default 0
Extend curve linearly at both ends? This may improve the appearance of fatbands ending at the edge of the plotting range.
 sgninteger, default +1
Direction of fatband outline. Coinciding outlines should be drawn in the same direction if omit is
True
. shiftslist of float
Displacements in weight direction of fatband.
 shortcutfloat, default 0
Maximum length of loop to be cut off.
 shortcut_relfloat, default 0.5
Maximum length of loop to be cut off relative to the total length of the curve. This is only used if shortcut is nonzero.
 thicknessfloat, default 1
Overall fatband linewidth scaling factor.
 weightslist of float
Fatband weights.
 xref, yreffloat, default None
Reference values for filled curves. This is useful to visualize integrands such as a density of states.
 zindesint, default None
Index of list of lines where new line is inserted. By default, the new line is appended to the list, i.e., has the highest zindex.
 **options
Local TikZ options.

node
(x, y, content, name=None, **options)¶ Draw (text) node at given position.
 Parameters
 x, yfloat
Node position in data coordinates.
 contentstr
Node content.
 namestr
Name/label to refer back to the node.
 **options
TikZ options of the node, e.g.,
above left=True
.

point
(x, y, name)¶ Define point.
 Parameters
 x, yfloat
Point position in data coordinates.
 namestr
Name/label to refer back to the point.

save
(filename, external=False, standalone=False, pdf=False)¶ Save plot to file.
 Parameters
 filenamestr
File name. If no period is contained, the
.tex
extension may be omitted. externalbool, default False
Provide file name to TikZ library
external
. standalonebool, default False
Create file that can be typeset with
pdflatex
, i.e., include document header etc.? pdfbool, default False
Typeset TeX file via
pdflatex
? This implied standalone.

storylines.
bonds
(R1, R2, d1=0.0, d2=0.0, dmin=0.1, dmax=5.0)¶ Find lines that connect two sets of points.
 Parameters
 R1, R2list of tuple
Two (ordered) sets of points.
 d1, d2float
Shortening on the two line ends.
 dmin, dmaxfloat
Minimum and maximum line length.
 Returns
 list of list of tuple
Connecting lines.

storylines.
combine
(filename, pdfs, columns=100, align=0.5, pdf=False)¶ Arrange multiple PDFs in single file.
 Parameters
 filenamestr
Name of combined file.
 pdfslist of str
Names of PDFs to be combined.
 columnsint, default 100
Number of PDFs to be arranged side by side.
 alignfloat, default 0.5
Vertical alignment of PDFs, where 0, 0.5, and 1 stand for the bottom, center, and top of the individual figures.
 pdfbool, default False
Convert resulting TeX file to PDF?

storylines.
cross
(A, B)¶ Calculate cross product of two vectors.
 Parameters
 A, Blist of float
Vectors to be multiplied.
 Returns
 float
Cross product of A and B.

storylines.
csv
(options)¶ Format TikZ options.
 Parameters
 optionsdict
TikZ options, where spaces in keys are represented by underscores.
 Returns
 str
Commaseparated keyvalue pairs in TikZ format.

storylines.
cut
(points, minimum, maximum, join=False)¶ Cut off curve segments beyond y interval.
 Parameters
 pointslist of 2tuples
Vertices of linear spline.
 minimum, maximumfloat
Lower and upper bound of y interval.
 joinbool
Concatenate remaining curve segments?
 Returns
 generator
Generator of remaining curve segments.
See also
cut
Similar function for 2D case.

storylines.
cut2d
(points, xmin, xmax, ymin, ymax, join=False)¶ Cut off curve segments beyond x and y intervals.
 Parameters
 pointslist of 2tuples
Vertices of linear spline.
 xmin, xmaxfloat
Lower and upper bound of x interval.
 ymin, ymaxfloat
Lower and upper bound of y interval.
 joinbool
Concatenate remaining curve segments?
 Returns
 generator
Generator of remaining curve segments.
See also
cut
Similar function for 1D case.

storylines.
dot
(A, B)¶ Calculate dot product of two vectors.
 Parameters
 A, Blist of float
Vectors to be multiplied.
 Returns
 float
Dot product of A and B.

storylines.
fatband
(points, width, weights, shifts, nib=None)¶ Represent weighted data points via varying linewidth.
 Parameters
 pointslist of 2tuples
Vertices of linear spline.
 widthfloat
Overall linewidth scaling factor.
 weightslist of float
Weights of points.
 shiftslist of float
Displacements in weight direction.
 nibfloat
Angle of broad pen nib. If
None
, the nib is held perpendicular to the direction of the line. The direction is always the average of the directions of adjacent line segments.
 Returns
 list of 2tuples
Fatband outline.
See also
miter_butt
Equivalent routine with miter line join.

storylines.
goto
(filename)¶ Go to output directory for plot typesetting.
 Parameters
 filenamestr
LaTeX file name including possible path.
 Returns
 stemstr
File name without path and extension.
 typesetfunction
Function to run
pdflatex
and remove.aux
and.log
files. homefunction
Function to return to previous working directory.

storylines.
groups
(iterable, size=4)¶ Group sequence of objects into chunks of given size.
 Parameters
 iterableiterable
Iterable sequence of objects.
 sizeint
Group size.
 Returns
 generator
Interator over groups of objects.

storylines.
islands
(N, criterion, join=False)¶ Select subranges of integer range.
 Parameters
 Ninteger
Length of original range.
 criterionfunction
Selection criterion for range members.
 joinbool
Concatenate all subranges?
 Returns
 generator
Generator of subrange lists.

storylines.
jump
(points, distance=1.0)¶ Interpret long line segments as discontinuities and omit them.
 Parameters
 pointslist of 2tuples
Vertices of linear spline.
 distancefloat
Shortest line segment to be omitted.
 Returns
 generator
Generator of separated curve segments.

storylines.
miter_butt
(points, width, weights, shifts, nib=None)¶ Represent weighted data points via varying linewidth.
 Parameters
 pointslist of 2tuples
Vertices of linear spline.
 widthfloat
Overall linewidth scaling factor.
 weightslist of float
Weights of points.
 shiftslist of float
Displacements in weight direction.
 nibfloat
Angle of broad pen nib. If
None
, the nib is held perpendicular to the direction of the current line segment. Line segments are connected using the miter joint.
 Returns
 list of 2tuples
Fatband outline.
See also
fatband
Equivalent routine without miter line join.

storylines.
multiples
(lower, upper, divisor=1)¶ Iterate over all integer multiples of given number on closed interval.
 Parameters
 lower, upperfloat
Bounds of closed interval.
 divisorfloat
Number the results shall be multiples of.
 Returns
 generator
Generator of all multiples of divisor between lower and upper.

storylines.
order_of_magnitude
(x)¶ Calculate the decimal order of magnitude.
 Parameters
 xfloat
Number of which to calculate the decimal order of magnitude.
 Returns
 int
Order of magnitude of x.

storylines.
power_of_ten
(x)¶ Calculate the power of ten of the same order of magnitude.
 Parameters
 xfloat
Number of which to calculate the power of ten of the same order of magnitude.
 Returns
 float
Power of ten of the same order of magnitude as x.

storylines.
project
(objects, *args, **kwargs)¶ Project list of 3D objects onto 2D screen.
Line width, mark sizes, and length in angle brackets are scaled according to the distance from the observer. The objects are sorted by distance so that close object overlay remote objects.
 Parameters
 objectslist of tuple
List of objects. Each object is represented by a tuple, which consists of a list of threetuples
(x, y, z)
and a style dictionary. *args, **kwargs
Arguments passed to projection.
 Returns
 list of tuple
Objects is same format, but sorted with transformed coordinates and adjusted styles.

storylines.
projection
(r=[0.0, 0.0, 0.0], R=[0.0,  1.0, 0.0], T=[0.0, 0.0, 0.0], U=[0.0, 0.0, 1.0])¶ Project 3D point onto 2D screen.
 Parameters
 Tlist of float
Object position.
 Rlist of float
Observer position.
 Tlist of float
Viewing direction (from observer).
 Ulist of float
Vertical direction.
 Returns
 list of float
x and y position as well as proximity factor z.

storylines.
relevant
(points, error=0.001)¶ Remove irrelevant vertices of linear spline.
 Parameters
 pointslist of 2tuples
Vertices of linear spline.
 errorfloat, optional
Tolerated deviation from original spline.
 Returns
 generator
Generator of thinned out vertices.

storylines.
shortcut
(points, length=None, length_rel=1)¶ Cut off loops at selfintersection points.
 Parameters
 pointslist of 2tuples
Vertices of linear spline.
 lengthfloat
Maximum length of loop to be cut off.
 length_relfloat
Maximum length of loop to be cut off relative to the total length of the curve.
 Returns
 list of 2tuples
Linear spline with selfintersection loops removed.

storylines.
xround
(x, divisor=1)¶ Round to multiple of given number.
 Parameters
 xfloat
Number to round.
 divisorfloat
Number the result shall be a multiple of.
 Returns
 float
x rounded to the closest multiple of divisor.

storylines.
xround_mantissa
(x, divisor=1)¶ Round mantissa to multiple of given number.
The mantissa is the part before the power of ten in scientific notation.
 Parameters
 xfloat
Number the mantissa of which to round.
 divisorfloat
Number the rounded mantissa shall be a multiple of.
 Returns
 float
x with the mantissa rounded to the closest multiple of divisor.