Core Module¶
Timeline¶
- class diplotocus.core.Timeline(name='Unnamed', fig=None, quiet=False, dpi=200, transparent=False, axis_color='k', noaxis=False, easing=<diplotocus.easings.easeLinear object>, xlim=None, ylim=None, figsize=None)[source]¶
Bases:
objectCreate and manage an animation timeline.
- Parameters:
name (str) – the name used for the rendered images folder.
fig (Figure | None) – an existing Figure to plot on. If None, a new Figure will be created.
quiet (bool) – if True, any message will not be printed, and no progress bar will be shown.
dpi (int) – The DPI of the rendered images (higher = better resolution/slower render).
transparent (bool) – if True, the background color of the Figure and axes will be transparent. Can be used to render a transparent video (only compatible with a .mov video file).
axis_color (str) – if True, changes the color of the axes, ticks and labels to the specified color.
noaxis (bool) – if True, hides the axis lines, ticks and labels.
easing (easing) – a global easing to be used if no other easing is specified on an animation.
xlim (tuple | None) – if fig is None, sets the X limits of the created axis.
ylim (tuple | None) – if fig is None, sets the Y limits of the created axis.
- animate(plot_objects, easing=None, debug=False)[source]¶
Render one or more plot objects into the timeline.
- save_video(path=None, speed=1, ffmpeg_path='ffmpeg', multialpha=False, prerendered=False, clean=True)[source]¶
Render the current timeline to a video file.
- Parameters:
path (str | None) – the path to save the video file to.
speed (float) – by default, animations are rendered at 30fps (frames per second). You can change this by setting the speed. For 60fps videos, choose speed=2.
ffmpeg_path (str) – if ffmpeg is not recognised as is, you can set the path to the ffmpeg executable through this parameter.
multialpha (bool) – when rendering to a transparent .mov video, if you have semi-transparent frames, can be used to get better results.
prerendered (bool) – if save_video() was already called and clean was set to False, image files and the text list file associated still exist. If you want to rerender the video, without having to rerender all the frames, you can set prerendered to true, which will only run the ffmpeg command.
clean (bool) – if True, image files and the text list file associated are deleted after the video has been rendered.
Animations¶
Base¶
- class diplotocus.animations.Animation(easing=None, axis=None, **kwargs)[source]¶
Bases:
objectA parent Animation object for all plotting objects.
- Parameters:
duration (float) – Duration of the animation
delay (float, default=0) – Delay before starting
easing (callable, optional) – Easing function
axis (matplotlib.axes.Axes, optional) – Axis to plot on
- draw(duration, reverse=False, delay=0, easing=None, persistent=True)[source]¶
Animate the plot object by sequentially adding more points of the dataset.
- Parameters:
duration (float) – the number of frames the animation runs from.
delay (float, default=0) – the number of frames after what the animation starts playing.
easing (callable, optional) – the easing used for this animation. If None, a linear easing is applied.
reverse (bool, default=False) – if True, removes points sequentially instead of adding points.
persistent (bool, default=True) – if True, the plot object will continue to be plotted after its last animation has played.
- hide(duration, delay=0, easing=None, persistent=True)[source]¶
Fade out plot objects.
This is a shorthand animation that fades out plot objects. It is equivalent to tween(‘alpha’,1,0).
- Parameters:
duration (float) – the number of frames the animation runs from.
delay (float, default=0) – the number of frames after what the animation starts playing.
easing (callable, optional) – the easing used for this animation. If None, a linear easing is applied.
persistent (bool, default=True) – if True, the plot object will continue to be plotted after its last animation has played.
- morph(new_x, new_y, duration, delay=0, easing=None, persistent=True)[source]¶
Morph between the base dataset and a new dataset.
- Parameters:
new_x (array-like or float) – the x data points to morph to.
new_y (array-like or float) – the y data points to morph to.
duration (float) – the number of frames the animation runs from.
delay (float, default=0) – the number of frames after what the animation starts playing.
easing (callable, optional) – the easing used for this animation. If None, a linear easing is applied.
persistent (bool, default=True) – if True, the plot object will continue to be plotted after its last animation has played.
hist()) (For plot objects that take 1D datasets (e.g.)
new_x. (morph() only accepts)
- rotate(start_angle, end_angle, duration, center=None, delay=0, easing=None, persistent=True)[source]¶
Rotate a plot object from one angle to another.
- Parameters:
start_angle (float) – the starting angle of the rotation in radians.
end_angle (float) – the ending angle of the rotation in radians.
duration (float) – the number of frames the animation runs from.
delay (float, default=0) – the number of frames after what the animation starts playing.
easing (callable, optional) – the easing used for this animation. If None, a linear easing is applied.
persistent (bool, default=True) – if True, the plot object will continue to be plotted after its last animation has played.
- scale(start_scale, end_scale, duration, center=None, delay=0, easing=None, persistent=True)[source]¶
Scale a plot object from one size to another.
- Parameters:
start_scale (float or tuple[float, float]) – the starting scale of the plot object.
end_scale (float or tuple[float, float]) – the ending scale of the plot object.
duration (float) – the number of frames the animation runs from.
delay (float, default=0) – the number of frames after what the animation starts playing.
easing (callable, optional) – the easing used for this animation. If None, a linear easing is applied.
persistent (bool, default=True) – if True, the plot object will continue to be plotted after its last animation has played.
values (You can either pass scalar)
scaled (in which case the plot object will be uniformly)
scales. (or a 2-tuple for independent X and Y)
- sequence(duration, delay=0, easing=None, persistent=True)[source]¶
Plot one datapoint or row of the dataset per frame.
- Parameters:
duration (float) – the number of frames the animation runs from.
delay (float, default=0) – the number of frames after what the animation starts playing.
easing (callable, optional) – the easing used for this animation. If None, a linear easing is applied.
persistent (bool, default=True) – if True, the plot object will continue to be plotted after its last animation has played.
1-dimensional (If the dataset is)
frame (this plots a single datapoint per)
2D (if)
frame-by-frame. (it will plot one row per frame. This animation can be used if you have a predefined list of datapoints you want to animate)
- show(duration, delay=0, easing=None, persistent=True)[source]¶
Fade in plot objects.
This is a shorthand animation that fades in plot objects. It is equivalent to tween(‘alpha’,0,1).
- Parameters:
duration (float) – the number of frames the animation runs from.
delay (float, default=0) – the number of frames after what the animation starts playing.
easing (callable, optional) – the easing used for this animation. If None, a linear easing is applied.
persistent (bool, default=True) – if True, the plot object will continue to be plotted after its last animation has played.
- translate(start_pos, end_pos, duration, delay=0, easing=None, persistent=True)[source]¶
Move a plot object from one position to another.
- Parameters:
start_pos (array-like) – where the translation starts, relative to the current center of the plot object.
end_pos (array-like) – where the translation ends, relative to the current center of the plot object.
duration (float) – the number of frames the animation runs from.
delay (float, default=0) – the number of frames after what the animation starts playing.
easing (callable, optional) – the easing used for this animation. If None, a linear easing is applied.
persistent (bool, default=True) – if True, the plot object will continue to be plotted after its last animation has played.
- tween(property, start, end, duration, delay=0, easing=None, persistent=True)[source]¶
Animate a change in a property of the plot object.
- Parameters:
property (str) – the name of the property to animate.
start (any) – the starting value of the property.
end (any) – the ending value of the property.
duration (float) – the number of frames the animation runs from.
delay (float, default=0) – the number of frames after what the animation starts playing.
easing (callable, optional) – the easing used for this animation. If None, a linear easing is applied.
- tweens(properties, starts, ends, duration, delay=0, easing=None, persistent=True)[source]¶
Animate multiple properties at once.
- Parameters:
properties (list[str]) – a list of the names of the properties to animate.
starts (list[Any]) – the starting values of the properties.
ends (list[Any]) – the ending values of the properties.
duration (float) – the number of frames the animation runs from.
delay (float, default=0) – the number of frames after what the animation starts playing.
easing (callable, optional) – the easing used for this animation. If None, a linear easing is applied.
Axis and figure animations¶
- class diplotocus.animations.axis_zoom(zoom, duration, delay=0, easing=None, axis=None, *args, **kwargs)[source]¶
Zooms into the axis given a zoom value.
- Parameters:
zoom (float) – Zoom level
duration (float) – Duration of the animation
delay (float, default=0) – Delay before starting
easing (callable, optional) – Easing function
axis (matplotlib.axes.Axes, optional) – Axis to plot on
Example
- Zoom 2 times in 100 frames:
>>> axis_zoom(zoom=2,duration=100)
- class diplotocus.animations.axis_limits(duration, xlim=None, ylim=None, delay=0, easing=None, axis=None, *args, **kwargs)[source]¶
Reframe axis to the given limits (on the x-axis, y-axis or both depending on passed arguments)
- Parameters:
xlim (array-like, default=None) – Target limits of the x-axis
ylim (array-like, default=None) – Target limits of the y-axis
duration (float) – Duration of the animation
delay (float, default=0) – Delay before starting
easing (callable, optional) – Easing function
axis (matplotlib.axes.Axes, optional) – Axis to plot on
Example
- Reframe x-axis to limits [0-2] in 100 frames:
>>> axis_limits(xlim=(0,2),duration=100)
- class diplotocus.animations.axis_move(end_pos, duration, start_pos=None, delay=0, easing=None, axis=None, *args, **kwargs)[source]¶
Move the center of the axis to a given position.
- Parameters:
pos (array-like) – Target center position
duration (float) – Duration of the animation
delay (float, default=0) – Delay before starting
easing (callable, optional) – Easing function
axis (matplotlib.axes.Axes, optional) – Axis to plot on
Example
- Recenter the axis to (-1,-1) in 100 frames:
>>> axis_move(pos=(-1,-1),duration=100)
- class diplotocus.animations.axis_alpha(start_alpha, end_alpha, duration, delay=0, alpha_objs=True, easing=None, axis=None, *args, **kwargs)[source]¶
Change the opacity of the axis.
- Parameters:
start_alpha (float) – Initial alpha value
end_alpha (float) – Final alpha value
duration (float) – Duration of the animation
delay (float, default=0) – Delay before starting
easing (callable, optional) – Easing function
axis (matplotlib.axes.Axes, optional) – Axis to plot on
Example
- Make the axis appear in 100 frames
>>> axis_alpha(start_alpha=0,end_alpha=1,duration=100)
- class diplotocus.animations.fig_width_ratio(start_widths, end_widths, duration, delay=0, easing=None, axis=None, *args, **kwargs)[source]¶
Resize subplots’ widths.
- Parameters:
start_widths (array-like) – Starting width ratios
end_widths (array-like) – End width ratios
duration (float) – Duration of the animation
delay (float, default=0) – Delay before starting
easing (callable, optional) – Easing function
axis (matplotlib.axes.Axes, optional) – Axis to plot on
Example
- Resize 2 subplots from equal widths to a ratio of 2:1 in 100 frames:
>>> fig_width_ratio(start_widths=(1,1),end_widths=(1,2),duration=100)
- class diplotocus.animations.fig_height_ratio(start_heights, end_heights, duration, delay=0, easing=None, axis=None, *args, **kwargs)[source]¶
Resize subplots’ heights.
- Parameters:
start_heights (array-like) – Starting height ratios
end_heights (array-like) – End height ratios
duration (float) – Duration of the animation
delay (float, default=0) – Delay before starting
easing (callable, optional) – Easing function
axis (matplotlib.axes.Axes, optional) – Axis to plot on
Example
- Resize 2 subplots from equal heights to a ratio of 2:1 in 100 frames:
>>> fig_width_ratio(start_heights=(1,1),end_heights=(1,2),duration=100)
Plot object animations¶
- class diplotocus.animations.scatter(x, y, easing=None, axis=None, *args, **kwargs)[source]¶
A scatter plot of y vs. x with varying marker size and/or color.
- Parameters:
x (float or array-like, shape (n, )) – The data positions.
y (float or array-like, shape (n, )) – The data positions.
duration (float) – Duration of the animation
delay (float, default=0) – Delay before starting
easing (callable, optional) – Easing function
axis (matplotlib.axes.Axes, optional) – Axis to plot on
- sfloat or array-like, shape (n, ), optional
The marker size in points**2 (typographic points are 1/72 in.). Default is
rcParams['lines.markersize'] ** 2.The linewidth and edgecolor can visually interact with the marker size, and can lead to artifacts if the marker size is smaller than the linewidth.
If the linewidth is greater than 0 and the edgecolor is anything but ‘none’, then the effective size of the marker will be increased by half the linewidth because the stroke will be centered on the edge of the shape.
To eliminate the marker edge either set linewidth=0 or edgecolor=’none’.
- carray-like or list of color or color, optional
The marker colors. Possible values:
A scalar or sequence of n numbers to be mapped to colors using cmap and norm.
A 2D array in which the rows are RGB or RGBA.
A sequence of colors of length n.
A single color format string.
Note that c should not be a single numeric RGB or RGBA sequence because that is indistinguishable from an array of values to be colormapped. If you want to specify the same RGB or RGBA value for all points, use a 2D array with a single row. Otherwise, value-matching will have precedence in case of a size matching with x and y.
If you wish to specify a single color for all points prefer the color keyword argument.
Defaults to None. In that case the marker color is determined by the value of color, facecolor or facecolors. In case those are not specified or None, the marker color is determined by the next color of the
Axes’ current “shape and fill” color cycle. This cycle defaults to axes.prop_cycle.- marker~.markers.MarkerStyle, default: scatter.marker
The marker style. marker can be either an instance of the class or the text shorthand for a particular marker. See
matplotlib.markersfor more information about marker styles.- cmapstr or ~matplotlib.colors.Colormap, default: image.cmap
The Colormap instance or registered colormap name used to map scalar data to colors.
This parameter is ignored if c is RGB(A).
- normstr or ~matplotlib.colors.Normalize, optional
The normalization method used to scale scalar data to the [0, 1] range before mapping to colors using cmap. By default, a linear scaling is used, mapping the lowest value to 0 and the highest to 1.
If given, this can be one of the following:
An instance of .Normalize or one of its subclasses (see Colormap normalization).
A scale name, i.e. one of “linear”, “log”, “symlog”, “logit”, etc. For a list of available scales, call matplotlib.scale.get_scale_names(). In that case, a suitable .Normalize subclass is dynamically generated and instantiated.
This parameter is ignored if c is RGB(A).
- vmin, vmaxfloat, optional
When using scalar data and no explicit norm, vmin and vmax define the data range that the colormap covers. By default, the colormap covers the complete value range of the supplied data. It is an error to use vmin/vmax when a norm instance is given (but using a str norm name together with vmin/vmax is acceptable).
This parameter is ignored if c is RGB(A).
- alphafloat, default: None
The alpha blending value, between 0 (transparent) and 1 (opaque).
- linewidthsfloat or array-like, default: lines.linewidth
The linewidth of the marker edges. Note: The default edgecolors is ‘face’. You may want to change this as well.
- edgecolors{‘face’, ‘none’, None} or color or list of color, default: scatter.edgecolors
The edge color of the marker. Possible values:
‘face’: The edge color will always be the same as the face color.
‘none’: No patch boundary will be drawn.
A color or sequence of colors.
For non-filled markers, edgecolors is ignored. Instead, the color is determined like with ‘face’, i.e. from c, colors, or facecolors.
- colorizer~matplotlib.colorizer.Colorizer or None, default: None
The Colorizer object used to map color to data. If None, a Colorizer object is created from a norm and cmap.
This parameter is ignored if c is RGB(A).
- plotnonfinitebool, default: False
Whether to plot points with nonfinite c (i.e.
inf,-infornan). IfTruethe points are drawn with the bad colormap color (see .Colormap.set_bad).
- Return type:
~matplotlib.collections.PathCollection
- Parameters:
data (indexable object, optional) –
If given, the following parameters also accept a string
s, which is interpreted asdata[s]ifsis a key indata:x, y, s, linewidths, edgecolors, c, facecolor, facecolors, color
**kwargs (~matplotlib.collections.PathCollection properties) – Properties: agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: array-like or float or None animated: bool antialiased or aa or antialiaseds: bool or list of bools array: array-like or None capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} clim: (vmin: float, vmax: float) clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None cmap: .Colormap or str or None color: color or list of RGBA tuples edgecolor or ec or edgecolors: color or list of color or ‘face’ facecolor or facecolors or fc: color or list of color figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure gid: str hatch: {‘/’, ‘', ‘|’, ‘-’, ‘+’, ‘x’, ‘o’, ‘O’, ‘.’, ‘*’} hatch_linewidth: unknown in_layout: bool joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} label: object linestyle or dashes or linestyles or ls: str or tuple or list thereof linewidth or linewidths or lw: float or list of floats mouseover: bool norm: .Normalize or str or None offset_transform or transOffset: .Transform offsets: (N, 2) or (2,) array-like path_effects: list of .AbstractPathEffect paths: unknown picker: None or bool or float or callable pickradius: float rasterized: bool sizes: numpy.ndarray or None sketch_params: (scale: float, length: float, randomness: float) snap: bool or None transform: ~matplotlib.transforms.Transform url: str urls: list of str or None visible: bool zorder: float
See also
plotTo plot scatter plots when markers are identical in size and color.
Notes
Note
This is the pyplot wrapper for .axes.Axes.scatter.
The .plot function will be faster for scatterplots where markers don’t vary in size or color.
Any or all of x, y, s, and c may be masked arrays, in which case all masks will be combined and only unmasked points will be plotted.
Fundamentally, scatter works with 1D arrays; x, y, s, and c may be input as N-D arrays, but within scatter they will be flattened. The exception is c, which will be flattened only if its size matches the size of x and y.
- class diplotocus.animations.plot(x, y, easing=None, axis=None, *args, **kwargs)[source]¶
Plot y versus x as lines and/or markers.
Call signatures:
plot([x], y, [fmt], *, data=None, **kwargs) plot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)
The coordinates of the points or line nodes are given by x, y.
The optional parameter fmt is a convenient way for defining basic formatting like color, marker and linestyle. It’s a shortcut string notation described in the Notes section below.
>>> plot(x, y) # plot x and y using default line style and color >>> plot(x, y, 'bo') # plot x and y using blue circle markers >>> plot(y) # plot y using x as index array 0..N-1 >>> plot(y, 'r+') # ditto, but with red plusses
You can use .Line2D properties as keyword arguments for more control on the appearance. Line properties and fmt can be mixed. The following two calls yield identical results:
>>> plot(x, y, 'go--', linewidth=2, markersize=12) >>> plot(x, y, color='green', marker='o', linestyle='dashed', ... linewidth=2, markersize=12)
When conflicting with fmt, keyword arguments take precedence.
Plotting labelled data
There’s a convenient way for plotting objects with labelled data (i.e. data that can be accessed by index
obj['y']). Instead of giving the data in x and y, you can provide the object in the data parameter and just give the labels for x and y:>>> plot('xlabel', 'ylabel', data=obj)
All indexable objects are supported. This could e.g. be a dict, a pandas.DataFrame or a structured numpy array.
Plotting multiple sets of data
There are various ways to plot multiple sets of data.
The most straight forward way is just to call plot multiple times. Example:
>>> plot(x1, y1, 'bo') >>> plot(x2, y2, 'go')
If x and/or y are 2D arrays, a separate data set will be drawn for every column. If both x and y are 2D, they must have the same shape. If only one of them is 2D with shape (N, m) the other must have length N and will be used for every data set m.
Example:
>>> x = [1, 2, 3] >>> y = np.array([[1, 2], [3, 4], [5, 6]]) >>> plot(x, y)
is equivalent to:
>>> for col in range(y.shape[1]): ... plot(x, y[:, col])
The third way is to specify multiple sets of [x], y, [fmt] groups:
>>> plot(x1, y1, 'g^', x2, y2, 'g-')
In this case, any additional keyword argument applies to all datasets. Also, this syntax cannot be combined with the data parameter.
By default, each line is assigned a different style specified by a ‘style cycle’. The fmt and line property parameters are only necessary if you want explicit deviations from these defaults. Alternatively, you can also change the style cycle using axes.prop_cycle.
- Parameters:
x (array-like or float) – The horizontal / vertical coordinates of the data points. x values are optional and default to
range(len(y)).y (array-like or float) – The horizontal / vertical coordinates of the data points. x values are optional and default to
range(len(y)).duration (float) – Duration of the animation
delay (float, default=0) – Delay before starting
easing (callable, optional) – Easing function
axis (matplotlib.axes.Axes, optional) – Axis to plot on
- fmtstr, optional
A format string, e.g. ‘ro’ for red circles. See the Notes section for a full description of the format strings.
Format strings are just an abbreviation for quickly setting basic line properties. All of these and more can also be controlled by keyword arguments.
This argument cannot be passed as keyword.
- dataindexable object, optional
An object with labelled data. If given, provide the label names to plot in x and y.
Note
Technically there’s a slight ambiguity in calls where the second label is a valid fmt.
plot('n', 'o', data=obj)could beplt(x, y)orplt(y, fmt). In such cases, the former interpretation is chosen, but a warning is issued. You may suppress the warning by adding an empty format stringplot('n', 'o', '', data=obj).
- Returns:
A list of lines representing the plotted data.
- Return type:
list of .Line2D
- Parameters:
scalex (bool, default: True) – These parameters determine if the view limits are adapted to the data limits. The values are passed on to ~.axes.Axes.autoscale_view.
scaley (bool, default: True) – These parameters determine if the view limits are adapted to the data limits. The values are passed on to ~.axes.Axes.autoscale_view.
**kwargs (~matplotlib.lines.Line2D properties, optional) –
kwargs are used to specify properties like a line label (for auto legends), linewidth, antialiasing, marker face color. Example:
>>> plot([1, 2, 3], [1, 2, 3], 'go-', label='line 1', linewidth=2) >>> plot([1, 2, 3], [1, 4, 9], 'rs', label='line 2')
If you specify multiple lines with one plot call, the kwargs apply to all those lines. In case the label object is iterable, each element is used as labels for each set of data.
Here is a list of available .Line2D properties:
Properties: agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: float or None animated: bool antialiased or aa: bool clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None color or c: color dash_capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} dash_joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} dashes: sequence of floats (on/off ink in points) or (None, None) data: (2, N) array or two 1D arrays drawstyle or ds: {‘default’, ‘steps’, ‘steps-pre’, ‘steps-mid’, ‘steps-post’}, default: ‘default’ figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure fillstyle: {‘full’, ‘left’, ‘right’, ‘bottom’, ‘top’, ‘none’} gapcolor: color or None gid: str in_layout: bool label: object linestyle or ls: {‘-’, ‘–’, ‘-.’, ‘:’, ‘’, (offset, on-off-seq), …} linewidth or lw: float marker: marker style string, ~.path.Path or ~.markers.MarkerStyle markeredgecolor or mec: color markeredgewidth or mew: float markerfacecolor or mfc: color markerfacecoloralt or mfcalt: color markersize or ms: float markevery: None or int or (int, int) or slice or list[int] or float or (float, float) or list[bool] mouseover: bool path_effects: list of .AbstractPathEffect picker: float or callable[[Artist, Event], tuple[bool, dict]] pickradius: float rasterized: bool sketch_params: (scale: float, length: float, randomness: float) snap: bool or None solid_capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} solid_joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} transform: unknown url: str visible: bool xdata: 1D array ydata: 1D array zorder: float
See also
scatterXY scatter plot with markers of varying size and/or color ( sometimes also called bubble chart).
Notes
Note
This is the pyplot wrapper for .axes.Axes.plot.
Format Strings
A format string consists of a part for color, marker and line:
fmt = '[marker][line][color]'
Each of them is optional. If not provided, the value from the style cycle is used. Exception: If
lineis given, but nomarker, the data will be a line without markers.Other combinations such as
[color][marker][line]are also supported, but note that their parsing may be ambiguous.Markers
character
description
'.'point marker
','pixel marker
'o'circle marker
'v'triangle_down marker
'^'triangle_up marker
'<'triangle_left marker
'>'triangle_right marker
'1'tri_down marker
'2'tri_up marker
'3'tri_left marker
'4'tri_right marker
'8'octagon marker
's'square marker
'p'pentagon marker
'P'plus (filled) marker
'*'star marker
'h'hexagon1 marker
'H'hexagon2 marker
'+'plus marker
'x'x marker
'X'x (filled) marker
'D'diamond marker
'd'thin_diamond marker
'|'vline marker
'_'hline marker
Line Styles
character
description
'-'solid line style
'--'dashed line style
'-.'dash-dot line style
':'dotted line style
Example format strings:
'b' # blue markers with default shape 'or' # red circles '-g' # green solid line '--' # dashed line with default color '^k:' # black triangle_up markers connected by a dotted line
Colors
The supported color abbreviations are the single letter codes
character
color
'b'blue
'g'green
'r'red
'c'cyan
'm'magenta
'y'yellow
'k'black
'w'white
and the
'CN'colors that index into the default property cycle.If the color is the only part of the format string, you can additionally use any matplotlib.colors spec, e.g. full names (
'green') or hex strings ('#008000').
- class diplotocus.animations.step(x, y, easing=None, axis=None, *args, **kwargs)[source]¶
Make a step plot.
Call signatures:
step(x, y, [fmt], *, data=None, where='pre', **kwargs) step(x, y, [fmt], x2, y2, [fmt2], ..., *, where='pre', **kwargs)
This is just a thin wrapper around .plot which changes some formatting options. Most of the concepts and parameters of plot can be used here as well.
Note
This method uses a standard plot with a step drawstyle: The x values are the reference positions and steps extend left/right/both directions depending on where.
For the common case where you know the values and edges of the steps, use ~.Axes.stairs instead.
- Parameters:
x (array-like) – 1D sequence of x positions. It is assumed, but not checked, that it is uniformly increasing.
y (array-like) – 1D sequence of y levels.
fmt (str, optional) –
A format string, e.g. ‘g’ for a green line. See .plot for a more detailed description.
Note: While full format strings are accepted, it is recommended to only specify the color. Line styles are currently ignored (use the keyword argument linestyle instead). Markers are accepted and plotted on the given positions, however, this is a rarely needed feature for step plots.
where ({'pre', 'post', 'mid'}, default: 'pre') –
Define where the steps should be placed:
- ’pre’: The y value is continued constantly to the left from
every x position, i.e. the interval
(x[i-1], x[i]]has the valuey[i].
- ’post’: The y value is continued constantly to the right from
every x position, i.e. the interval
[x[i], x[i+1])has the valuey[i].
’mid’: Steps occur half-way between the x positions.
data (indexable object, optional) – An object with labelled data. If given, provide the label names to plot in x and y.
**kwargs – Additional parameters are the same as those for .plot.
- Returns:
Objects representing the plotted data.
- Return type:
list of .Line2D
- class diplotocus.animations.fill_between(x, y1, y2, easing=None, axis=None, *args, **kwargs)[source]¶
Fill the area between two horizontal curves.
The curves are defined by the points (x, y1) and (x, y2). This creates one or multiple polygons describing the filled area.
You may exclude some horizontal sections from filling using where.
By default, the edges connect the given points directly. Use step if the filling should be a step function, i.e. constant in between x.
- Parameters:
x (array-like) – The x coordinates of the nodes defining the curves.
duration (float) – Duration of the animation
delay (float, default=0) – Delay before starting
easing (callable, optional) – Easing function
axis (matplotlib.axes.Axes, optional) – Axis to plot on
- y1array-like or float
The y coordinates of the nodes defining the first curve.
- y2array-like or float, default: 0
The y coordinates of the nodes defining the second curve.
- wherearray-like of bool, optional
Define where to exclude some horizontal regions from being filled. The filled regions are defined by the coordinates
x[where]. More precisely, fill betweenx[i]andx[i+1]ifwhere[i] and where[i+1]. Note that this definition implies that an isolated True value between two False values in where will not result in filling. Both sides of the True position remain unfilled due to the adjacent False values.- interpolatebool, default: False
This option is only relevant if where is used and the two curves are crossing each other.
Semantically, where is often used for y1 > y2 or similar. By default, the nodes of the polygon defining the filled region will only be placed at the positions in the x array. Such a polygon cannot describe the above semantics close to the intersection. The x-sections containing the intersection are simply clipped.
Setting interpolate to True will calculate the actual intersection point and extend the filled region up to this point.
- step{‘pre’, ‘post’, ‘mid’}, optional
Define step if the filling should be a step function, i.e. constant in between x. The value determines where the step will occur:
‘pre’: The y value is continued constantly to the left from every x position, i.e. the interval
(x[i-1], x[i]]has the valuey[i].‘post’: The y value is continued constantly to the right from every x position, i.e. the interval
[x[i], x[i+1])has the valuey[i].‘mid’: Steps occur half-way between the x positions.
- Returns:
A .FillBetweenPolyCollection containing the plotted polygons.
- Return type:
.FillBetweenPolyCollection
- Parameters:
data (indexable object, optional) –
If given, the following parameters also accept a string
s, which is interpreted asdata[s]ifsis a key indata:x, y1, y2, where
**kwargs –
All other keyword arguments are passed on to .FillBetweenPolyCollection. They control the .Polygon properties:
Properties: agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: array-like or float or None animated: bool antialiased or aa or antialiaseds: bool or list of bools array: array-like or None capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} clim: (vmin: float, vmax: float) clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None cmap: .Colormap or str or None color: color or list of RGBA tuples data: array-like edgecolor or ec or edgecolors: color or list of color or ‘face’ facecolor or facecolors or fc: color or list of color figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure gid: str hatch: {‘/’, ‘', ‘|’, ‘-’, ‘+’, ‘x’, ‘o’, ‘O’, ‘.’, ‘*’} hatch_linewidth: unknown in_layout: bool joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} label: object linestyle or dashes or linestyles or ls: str or tuple or list thereof linewidth or linewidths or lw: float or list of floats mouseover: bool norm: .Normalize or str or None offset_transform or transOffset: .Transform offsets: (N, 2) or (2,) array-like path_effects: list of .AbstractPathEffect paths: list of array-like picker: None or bool or float or callable pickradius: float rasterized: bool sizes: numpy.ndarray or None sketch_params: (scale: float, length: float, randomness: float) snap: bool or None transform: ~matplotlib.transforms.Transform url: str urls: list of str or None verts: list of array-like verts_and_codes: unknown visible: bool zorder: float
See also
fill_betweenFill between two sets of y-values.
fill_betweenxFill between two sets of x-values.
Notes
Note
This is the pyplot wrapper for .axes.Axes.fill_between.
- class diplotocus.animations.fill_betweenx(y, x1, x2, easing=None, axis=None, *args, **kwargs)[source]¶
Fill the area between two vertical curves.
The curves are defined by the points (y, x1) and (y, x2). This creates one or multiple polygons describing the filled area.
You may exclude some vertical sections from filling using where.
By default, the edges connect the given points directly. Use step if the filling should be a step function, i.e. constant in between y.
- Parameters:
y (array-like) – The y coordinates of the nodes defining the curves.
duration (float) – Duration of the animation
delay (float, default=0) – Delay before starting
easing (callable, optional) – Easing function
axis (matplotlib.axes.Axes, optional) – Axis to plot on
- x1array-like or float
The x coordinates of the nodes defining the first curve.
- x2array-like or float, default: 0
The x coordinates of the nodes defining the second curve.
- wherearray-like of bool, optional
Define where to exclude some vertical regions from being filled. The filled regions are defined by the coordinates
y[where]. More precisely, fill betweeny[i]andy[i+1]ifwhere[i] and where[i+1]. Note that this definition implies that an isolated True value between two False values in where will not result in filling. Both sides of the True position remain unfilled due to the adjacent False values.- interpolatebool, default: False
This option is only relevant if where is used and the two curves are crossing each other.
Semantically, where is often used for x1 > x2 or similar. By default, the nodes of the polygon defining the filled region will only be placed at the positions in the y array. Such a polygon cannot describe the above semantics close to the intersection. The y-sections containing the intersection are simply clipped.
Setting interpolate to True will calculate the actual intersection point and extend the filled region up to this point.
- step{‘pre’, ‘post’, ‘mid’}, optional
Define step if the filling should be a step function, i.e. constant in between y. The value determines where the step will occur:
‘pre’: The x value is continued constantly to the left from every y position, i.e. the interval
(y[i-1], y[i]]has the valuex[i].‘post’: The y value is continued constantly to the right from every y position, i.e. the interval
[y[i], y[i+1])has the valuex[i].‘mid’: Steps occur half-way between the y positions.
- Returns:
A .FillBetweenPolyCollection containing the plotted polygons.
- Return type:
.FillBetweenPolyCollection
- Parameters:
data (indexable object, optional) –
If given, the following parameters also accept a string
s, which is interpreted asdata[s]ifsis a key indata:y, x1, x2, where
**kwargs –
All other keyword arguments are passed on to .FillBetweenPolyCollection. They control the .Polygon properties:
Properties: agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: array-like or float or None animated: bool antialiased or aa or antialiaseds: bool or list of bools array: array-like or None capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} clim: (vmin: float, vmax: float) clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None cmap: .Colormap or str or None color: color or list of RGBA tuples data: array-like edgecolor or ec or edgecolors: color or list of color or ‘face’ facecolor or facecolors or fc: color or list of color figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure gid: str hatch: {‘/’, ‘', ‘|’, ‘-’, ‘+’, ‘x’, ‘o’, ‘O’, ‘.’, ‘*’} hatch_linewidth: unknown in_layout: bool joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} label: object linestyle or dashes or linestyles or ls: str or tuple or list thereof linewidth or linewidths or lw: float or list of floats mouseover: bool norm: .Normalize or str or None offset_transform or transOffset: .Transform offsets: (N, 2) or (2,) array-like path_effects: list of .AbstractPathEffect paths: list of array-like picker: None or bool or float or callable pickradius: float rasterized: bool sizes: numpy.ndarray or None sketch_params: (scale: float, length: float, randomness: float) snap: bool or None transform: ~matplotlib.transforms.Transform url: str urls: list of str or None verts: list of array-like verts_and_codes: unknown visible: bool zorder: float
See also
fill_betweenFill between two sets of y-values.
fill_betweenxFill between two sets of x-values.
Notes
Note
This is the pyplot wrapper for .axes.Axes.fill_betweenx.
- class diplotocus.animations.axvline(x, easing=None, axis=None, *args, **kwargs)[source]¶
Add a vertical line spanning the whole or fraction of the Axes.
Note: If you want to set y-limits in data coordinates, use ~.Axes.vlines instead.
- Parameters:
x (float, default: 0) – x position in data coordinates.
duration (float) – Duration of the animation
delay (float, default=0) – Delay before starting
easing (callable, optional) – Easing function
axis (matplotlib.axes.Axes, optional) – Axis to plot on
- yminfloat, default: 0
The start y-position in axes coordinates. Should be between 0 and 1, 0 being the bottom of the plot, 1 the top of the plot.
- ymaxfloat, default: 1
The end y-position in axes coordinates. Should be between 0 and 1, 0 being the bottom of the plot, 1 the top of the plot.
- Returns:
A .Line2D specified via two points
(x, ymin),(x, ymax). Its transform is set such that x is in data coordinates and y is in axes coordinates.This is still a generic line and the vertical character is only realized through using identical x values for both points. Thus, if you want to change the x value later, you have to provide two values
line.set_xdata([3, 3]).- Return type:
~matplotlib.lines.Line2D
- Parameters:
**kwargs –
Valid keyword arguments are .Line2D properties, except for ‘transform’:
Properties: agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: float or None animated: bool antialiased or aa: bool clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None color or c: color dash_capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} dash_joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} dashes: sequence of floats (on/off ink in points) or (None, None) data: (2, N) array or two 1D arrays drawstyle or ds: {‘default’, ‘steps’, ‘steps-pre’, ‘steps-mid’, ‘steps-post’}, default: ‘default’ figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure fillstyle: {‘full’, ‘left’, ‘right’, ‘bottom’, ‘top’, ‘none’} gapcolor: color or None gid: str in_layout: bool label: object linestyle or ls: {‘-’, ‘–’, ‘-.’, ‘:’, ‘’, (offset, on-off-seq), …} linewidth or lw: float marker: marker style string, ~.path.Path or ~.markers.MarkerStyle markeredgecolor or mec: color markeredgewidth or mew: float markerfacecolor or mfc: color markerfacecoloralt or mfcalt: color markersize or ms: float markevery: None or int or (int, int) or slice or list[int] or float or (float, float) or list[bool] mouseover: bool path_effects: list of .AbstractPathEffect picker: float or callable[[Artist, Event], tuple[bool, dict]] pickradius: float rasterized: bool sketch_params: (scale: float, length: float, randomness: float) snap: bool or None solid_capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} solid_joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} transform: unknown url: str visible: bool xdata: 1D array ydata: 1D array zorder: float
See also
vlinesAdd vertical lines in data coordinates.
axvspanAdd a vertical span (rectangle) across the axis.
axlineAdd a line with an arbitrary slope.
Notes
Note
This is the pyplot wrapper for .axes.Axes.axvline.
Examples
draw a thick red vline at x = 0 that spans the yrange:
>>> axvline(linewidth=4, color='r')
draw a default vline at x = 1 that spans the yrange:
>>> axvline(x=1)
draw a default vline at x = .5 that spans the middle half of the yrange:
>>> axvline(x=.5, ymin=0.25, ymax=0.75)
- class diplotocus.animations.axhline(y, easing=None, axis=None, *args, **kwargs)[source]¶
Add a horizontal line spanning the whole or fraction of the Axes.
Note: If you want to set x-limits in data coordinates, use ~.Axes.hlines instead.
- Parameters:
y (float, default: 0) – y position in data coordinates.
xmin (float, default: 0) – The start x-position in axes coordinates. Should be between 0 and 1, 0 being the far left of the plot, 1 the far right of the plot.
xmax (float, default: 1) – The end x-position in axes coordinates. Should be between 0 and 1, 0 being the far left of the plot, 1 the far right of the plot.
**kwargs –
Valid keyword arguments are .Line2D properties, except for ‘transform’:
%(Line2D:kwdoc)s
- Returns:
A .Line2D specified via two points
(xmin, y),(xmax, y). Its transform is set such that x is in axes coordinates and y is in data coordinates.This is still a generic line and the horizontal character is only realized through using identical y values for both points. Thus, if you want to change the y value later, you have to provide two values
line.set_ydata([3, 3]).- Return type:
~matplotlib.lines.Line2D
See also
hlinesAdd horizontal lines in data coordinates.
axhspanAdd a horizontal span (rectangle) across the axis.
axlineAdd a line with an arbitrary slope.
Examples
draw a thick red hline at ‘y’ = 0 that spans the xrange:
>>> axhline(linewidth=4, color='r')
draw a default hline at ‘y’ = 1 that spans the xrange:
>>> axhline(y=1)
- draw a default hline at ‘y’ = .5 that spans the middle half of
the xrange:
>>> axhline(y=.5, xmin=0.25, xmax=0.75)
- class diplotocus.animations.errorbar(x, y, xerr=None, yerr=None, easing=None, axis=None, *args, **kwargs)[source]¶
Plot y versus x as lines and/or markers with attached errorbars.
x, y define the data locations, xerr, yerr define the errorbar sizes. By default, this draws the data markers/lines as well as the errorbars. Use fmt=’none’ to draw errorbars without any data markers.
Added in version 3.7: Caps and error lines are drawn in polar coordinates on polar plots.
- Parameters:
x (float or array-like) – The data positions.
y (float or array-like) – The data positions.
duration (float) – Duration of the animation
delay (float, default=0) – Delay before starting
easing (callable, optional) – Easing function
axis (matplotlib.axes.Axes, optional) – Axis to plot on
- xerr, yerrfloat or array-like, shape(N,) or shape(2, N), optional
The errorbar sizes:
scalar: Symmetric +/- values for all data points.
shape(N,): Symmetric +/-values for each data point.
shape(2, N): Separate - and + values for each bar. First row contains the lower errors, the second row contains the upper errors.
None: No errorbar.
All values must be >= 0.
- fmtstr, default: ‘’
The format for the data points / data lines. See .plot for details.
Use ‘none’ (case-insensitive) to plot errorbars without any data markers.
- ecolorcolor, default: None
The color of the errorbar lines. If None, use the color of the line connecting the markers.
- elinewidthfloat, default: None
The linewidth of the errorbar lines. If None, the linewidth of the current style is used.
- capsizefloat, default: errorbar.capsize
The length of the error bar caps in points.
- capthickfloat, default: None
An alias to the keyword argument markeredgewidth (a.k.a. mew). This setting is a more sensible name for the property that controls the thickness of the error bar cap in points. For backwards compatibility, if mew or markeredgewidth are given, then they will over-ride capthick. This may change in future releases.
- barsabovebool, default: False
If True, will plot the errorbars above the plot symbols. Default is below.
- lolims, uplims, xlolims, xuplimsbool or array-like, default: False
These arguments can be used to indicate that a value gives only upper/lower limits. In that case a caret symbol is used to indicate this. lims-arguments may be scalars, or array-likes of the same length as xerr and yerr. To use limits with inverted axes, ~.Axes.set_xlim or ~.Axes.set_ylim must be called before
errorbar(). Note the tricky parameter names: setting e.g. lolims to True means that the y-value is a lower limit of the True value, so, only an upward-pointing arrow will be drawn!- erroreveryint or (int, int), default: 1
draws error bars on a subset of the data. errorevery =N draws error bars on the points (x[::N], y[::N]). errorevery =(start, N) draws error bars on the points (x[start::N], y[start::N]). e.g. errorevery=(6, 3) adds error bars to the data at (x[6], x[9], x[12], x[15], …). Used to avoid overlapping error bars when two series share x-axis values.
- Returns:
The container contains:
data_line : A ~matplotlib.lines.Line2D instance of x, y plot markers and/or line.
caplines : A tuple of ~matplotlib.lines.Line2D instances of the error bar caps.
barlinecols : A tuple of .LineCollection with the horizontal and vertical error ranges.
- Return type:
.ErrorbarContainer
- Parameters:
data (indexable object, optional) –
If given, the following parameters also accept a string
s, which is interpreted asdata[s]ifsis a key indata:x, y, xerr, yerr
**kwargs –
All other keyword arguments are passed on to the ~.Axes.plot call drawing the markers. For example, this code makes big red squares with thick green edges:
x, y, yerr = rand(3, 10) errorbar(x, y, yerr, marker='s', mfc='red', mec='green', ms=20, mew=4)
where mfc, mec, ms and mew are aliases for the longer property names, markerfacecolor, markeredgecolor, markersize and markeredgewidth.
Valid kwargs for the marker properties are:
dashes
dash_capstyle
dash_joinstyle
drawstyle
fillstyle
linestyle
marker
markeredgecolor
markeredgewidth
markerfacecolor
markerfacecoloralt
markersize
markevery
solid_capstyle
solid_joinstyle
Refer to the corresponding .Line2D property for more details:
Properties: agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: float or None animated: bool antialiased or aa: bool clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None color or c: color dash_capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} dash_joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} dashes: sequence of floats (on/off ink in points) or (None, None) data: (2, N) array or two 1D arrays drawstyle or ds: {‘default’, ‘steps’, ‘steps-pre’, ‘steps-mid’, ‘steps-post’}, default: ‘default’ figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure fillstyle: {‘full’, ‘left’, ‘right’, ‘bottom’, ‘top’, ‘none’} gapcolor: color or None gid: str in_layout: bool label: object linestyle or ls: {‘-’, ‘–’, ‘-.’, ‘:’, ‘’, (offset, on-off-seq), …} linewidth or lw: float marker: marker style string, ~.path.Path or ~.markers.MarkerStyle markeredgecolor or mec: color markeredgewidth or mew: float markerfacecolor or mfc: color markerfacecoloralt or mfcalt: color markersize or ms: float markevery: None or int or (int, int) or slice or list[int] or float or (float, float) or list[bool] mouseover: bool path_effects: list of .AbstractPathEffect picker: float or callable[[Artist, Event], tuple[bool, dict]] pickradius: float rasterized: bool sketch_params: (scale: float, length: float, randomness: float) snap: bool or None solid_capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} solid_joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} transform: unknown url: str visible: bool xdata: 1D array ydata: 1D array zorder: float
Notes
Note
This is the pyplot wrapper for .axes.Axes.errorbar.
- morph(new_x, new_y, duration, new_xerr=None, new_yerr=None, delay=0, easing=None, persistent=True)[source]¶
Morph between the base dataset and a new dataset.
- Parameters:
new_x (array-like or float) – the x data points to morph to.
new_y (array-like or float) – the y data points to morph to.
duration (float) – the number of frames the animation runs from.
delay (float, default=0) – the number of frames after what the animation starts playing.
easing (callable, optional) – the easing used for this animation. If None, a linear easing is applied.
persistent (bool, default=True) – if True, the plot object will continue to be plotted after its last animation has played.
hist()) (For plot objects that take 1D datasets (e.g.)
new_x. (morph() only accepts)
- class diplotocus.animations.hist(x, easing=None, axis=None, *args, **kwargs)[source]¶
Compute and plot a histogram.
This method uses numpy.histogram to bin the data in x and count the number of values in each bin, then draws the distribution either as a .BarContainer or .Polygon. The bins, range, density, and weights parameters are forwarded to numpy.histogram.
If the data has already been binned and counted, use ~.bar or ~.stairs to plot the distribution:
counts, bins = np.histogram(x) plt.stairs(counts, bins)
Alternatively, plot pre-computed bins and counts using
hist()by treating each bin as a single point with a weight equal to its count:plt.hist(bins[:-1], bins, weights=counts)
The data input x can be a singular array, a list of datasets of potentially different lengths ([x0, x1, …]), or a 2D ndarray in which each column is a dataset. Note that the ndarray form is transposed relative to the list form. If the input is an array, then the return value is a tuple (n, bins, patches); if the input is a sequence of arrays, then the return value is a tuple ([n0, n1, …], bins, [patches0, patches1, …]).
Masked arrays are not supported.
- Parameters:
x ((n,) array or sequence of (n,) arrays) – Input values, this takes either a single array or a sequence of arrays which are not required to be of the same length.
duration (float) – Duration of the animation
delay (float, default=0) – Delay before starting
easing (callable, optional) – Easing function
axis (matplotlib.axes.Axes, optional) – Axis to plot on
- binsint or sequence or str, default: hist.bins
If bins is an integer, it defines the number of equal-width bins in the range.
If bins is a sequence, it defines the bin edges, including the left edge of the first bin and the right edge of the last bin; in this case, bins may be unequally spaced. All but the last (righthand-most) bin is half-open. In other words, if bins is:
[1, 2, 3, 4]
then the first bin is
[1, 2)(including 1, but excluding 2) and the second[2, 3). The last bin, however, is[3, 4], which includes 4.If bins is a string, it is one of the binning strategies supported by numpy.histogram_bin_edges: ‘auto’, ‘fd’, ‘doane’, ‘scott’, ‘stone’, ‘rice’, ‘sturges’, or ‘sqrt’.
- rangetuple or None, default: None
The lower and upper range of the bins. Lower and upper outliers are ignored. If not provided, range is
(x.min(), x.max()). Range has no effect if bins is a sequence.If bins is a sequence or range is specified, autoscaling is based on the specified bin range instead of the range of x.
- densitybool, default: False
If
True, draw and return a probability density: each bin will display the bin’s raw count divided by the total number of counts and the bin width (density = counts / (sum(counts) * np.diff(bins))), so that the area under the histogram integrates to 1 (np.sum(density * np.diff(bins)) == 1).If stacked is also
True, the sum of the histograms is normalized to 1.- weights(n,) array-like or None, default: None
An array of weights, of the same shape as x. Each value in x only contributes its associated weight towards the bin count (instead of 1). If density is
True, the weights are normalized, so that the integral of the density over the range remains 1.- cumulativebool or -1, default: False
If
True, then a histogram is computed where each bin gives the counts in that bin plus all bins for smaller values. The last bin gives the total number of datapoints.If density is also
Truethen the histogram is normalized such that the last bin equals 1.If cumulative is a number less than 0 (e.g., -1), the direction of accumulation is reversed. In this case, if density is also
True, then the histogram is normalized such that the first bin equals 1.- bottomarray-like or float, default: 0
Location of the bottom of each bin, i.e. bins are drawn from
bottomtobottom + hist(x, bins)If a scalar, the bottom of each bin is shifted by the same amount. If an array, each bin is shifted independently and the length of bottom must match the number of bins. If None, defaults to 0.- histtype{‘bar’, ‘barstacked’, ‘step’, ‘stepfilled’}, default: ‘bar’
The type of histogram to draw.
‘bar’ is a traditional bar-type histogram. If multiple data are given the bars are arranged side by side.
‘barstacked’ is a bar-type histogram where multiple data are stacked on top of each other.
‘step’ generates a lineplot that is by default unfilled.
‘stepfilled’ generates a lineplot that is by default filled.
- align{‘left’, ‘mid’, ‘right’}, default: ‘mid’
The horizontal alignment of the histogram bars.
‘left’: bars are centered on the left bin edges.
‘mid’: bars are centered between the bin edges.
‘right’: bars are centered on the right bin edges.
- orientation{‘vertical’, ‘horizontal’}, default: ‘vertical’
If ‘horizontal’, ~.Axes.barh will be used for bar-type histograms and the bottom kwarg will be the left edges.
- rwidthfloat or None, default: None
The relative width of the bars as a fraction of the bin width. If
None, automatically compute the width.Ignored if histtype is ‘step’ or ‘stepfilled’.
- logbool, default: False
If
True, the histogram axis will be set to a log scale.- colorcolor or list of color or None, default: None
Color or sequence of colors, one per dataset. Default (
None) uses the standard line color sequence.- labelstr or list of str, optional
String, or sequence of strings to match multiple datasets. Bar charts yield multiple patches per dataset, but only the first gets the label, so that ~.Axes.legend will work as expected.
- stackedbool, default: False
If
True, multiple data are stacked on top of each other IfFalsemultiple data are arranged side by side if histtype is ‘bar’ or on top of each other if histtype is ‘step’
- Returns:
n (array or list of arrays) – The values of the histogram bins. See density and weights for a description of the possible semantics. If input x is an array, then this is an array of length nbins. If input is a sequence of arrays
[data1, data2, ...], then this is a list of arrays with the values of the histograms for each of the arrays in the same order. The dtype of the array n (or of its element arrays) will always be float even if no weighting or normalization is used.bins (array) – The edges of the bins. Length nbins + 1 (nbins left edges and right edge of last bin). Always a single array even when multiple data sets are passed in.
patches (.BarContainer or list of a single .Polygon or list of such objects) – Container of individual artists used to create the histogram or list of such containers if there are multiple input datasets.
- Parameters:
data (indexable object, optional) –
If given, the following parameters also accept a string
s, which is interpreted asdata[s]ifsis a key indata:x, weights
**kwargs –
~matplotlib.patches.Patch properties. The following properties additionally accept a sequence of values corresponding to the datasets in x: edgecolor, facecolor, linewidth, linestyle, hatch.
Added in version 3.10: Allowing sequences of values in above listed Patch properties.
See also
hist2d2D histogram with rectangular bins
hexbin2D histogram with hexagonal bins
stairsPlot a pre-computed histogram
barPlot a pre-computed histogram
Notes
Note
This is the pyplot wrapper for .axes.Axes.hist.
For large numbers of bins (>1000), plotting can be significantly accelerated by using ~.Axes.stairs to plot a pre-computed histogram (
plt.stairs(*np.histogram(data))), or by setting histtype to ‘step’ or ‘stepfilled’ rather than ‘bar’ or ‘barstacked’.- morph(new_x, duration, delay=0, easing=None, persistent=True, **kwargs)[source]¶
Morph between the base dataset and a new dataset.
- Parameters:
new_x (array-like or float) – the x data points to morph to.
new_y (array-like or float) – the y data points to morph to.
duration (float) – the number of frames the animation runs from.
delay (float, default=0) – the number of frames after what the animation starts playing.
easing (callable, optional) – the easing used for this animation. If None, a linear easing is applied.
persistent (bool, default=True) – if True, the plot object will continue to be plotted after its last animation has played.
hist()) (For plot objects that take 1D datasets (e.g.)
new_x. (morph() only accepts)
- class diplotocus.animations.hist2d(x, y, easing=None, axis=None, *args, **kwargs)[source]¶
Make a 2D histogram plot.
- Parameters:
x (array-like, shape (n, )) – Input values
y (array-like, shape (n, )) – Input values
duration (float) – Duration of the animation
delay (float, default=0) – Delay before starting
easing (callable, optional) – Easing function
axis (matplotlib.axes.Axes, optional) – Axis to plot on
bins : None or int or [int, int] or array-like or [array, array]
The bin specification:
If int, the number of bins for the two dimensions (
nx = ny = bins).If
[int, int], the number of bins in each dimension (nx, ny = bins).If array-like, the bin edges for the two dimensions (
x_edges = y_edges = bins).If
[array, array], the bin edges in each dimension (x_edges, y_edges = bins).
The default value is 10.
- rangearray-like shape(2, 2), optional
The leftmost and rightmost edges of the bins along each dimension (if not specified explicitly in the bins parameters):
[[xmin, xmax], [ymin, ymax]]. All values outside of this range will be considered outliers and not tallied in the histogram.- densitybool, default: False
Normalize histogram. See the documentation for the density parameter of ~.Axes.hist for more details.
- weightsarray-like, shape (n, ), optional
An array of values w_i weighing each sample (x_i, y_i).
- cmin, cmaxfloat, default: None
All bins that has count less than cmin or more than cmax will not be displayed (set to NaN before passing to ~.Axes.pcolormesh) and these count values in the return value count histogram will also be set to nan upon return.
- Returns:
h (2D array) – The bi-dimensional histogram of samples x and y. Values in x are histogrammed along the first dimension and values in y are histogrammed along the second dimension.
xedges (1D array) – The bin edges along the x-axis.
yedges (1D array) – The bin edges along the y-axis.
image (~.matplotlib.collections.QuadMesh)
- Parameters:
cmap (str or ~matplotlib.colors.Colormap, default: image.cmap) – The Colormap instance or registered colormap name used to map scalar data to colors.
norm (str or ~matplotlib.colors.Normalize, optional) –
The normalization method used to scale scalar data to the [0, 1] range before mapping to colors using cmap. By default, a linear scaling is used, mapping the lowest value to 0 and the highest to 1.
If given, this can be one of the following:
An instance of .Normalize or one of its subclasses (see Colormap normalization).
A scale name, i.e. one of “linear”, “log”, “symlog”, “logit”, etc. For a list of available scales, call matplotlib.scale.get_scale_names(). In that case, a suitable .Normalize subclass is dynamically generated and instantiated.
vmin (float, optional) – When using scalar data and no explicit norm, vmin and vmax define the data range that the colormap covers. By default, the colormap covers the complete value range of the supplied data. It is an error to use vmin/vmax when a norm instance is given (but using a str norm name together with vmin/vmax is acceptable).
vmax (float, optional) – When using scalar data and no explicit norm, vmin and vmax define the data range that the colormap covers. By default, the colormap covers the complete value range of the supplied data. It is an error to use vmin/vmax when a norm instance is given (but using a str norm name together with vmin/vmax is acceptable).
colorizer (~matplotlib.colorizer.Colorizer or None, default: None) – The Colorizer object used to map color to data. If None, a Colorizer object is created from a norm and cmap.
alpha (
0 <= scalar <= 1orNone, optional) – The alpha blending value.data (indexable object, optional) –
If given, the following parameters also accept a string
s, which is interpreted asdata[s]ifsis a key indata:x, y, weights
**kwargs – Additional parameters are passed along to the ~.Axes.pcolormesh method and ~matplotlib.collections.QuadMesh constructor.
See also
hist1D histogram plotting
hexbin2D histogram with hexagonal bins
Notes
Note
This is the pyplot wrapper for .axes.Axes.hist2d.
Currently
hist2dcalculates its own axis limits, and any limits previously set are ignored.Rendering the histogram with a logarithmic color scale is accomplished by passing a .colors.LogNorm instance to the norm keyword argument. Likewise, power-law normalization (similar in effect to gamma correction) can be accomplished with .colors.PowerNorm.
- class diplotocus.animations.contourf(z, x=None, y=None, easing=None, axis=None, *args, **kwargs)[source]¶
Plot filled contours.
Call signature:
contourf([X, Y,] Z, /, [levels], **kwargs)
The arguments X, Y, Z are positional-only.
.contour and .contourf draw contour lines and filled contours, respectively. Except as noted, function signatures and return values are the same for both versions.
- Parameters:
X (array-like, optional) – The coordinates of the values in Z.
Y (array-like, optional) – The coordinates of the values in Z.
duration (float) – Duration of the animation
delay (float, default=0) – Delay before starting
easing (callable, optional) – Easing function
axis (matplotlib.axes.Axes, optional) – Axis to plot on
- Z(M, N) array-like
The height values over which the contour is drawn. Color-mapping is controlled by cmap, norm, vmin, and vmax.
- levelsint or array-like, optional
Determines the number and positions of the contour lines / regions.
If an int n, use ~matplotlib.ticker.MaxNLocator, which tries to automatically choose no more than n+1 “nice” contour levels between minimum and maximum numeric values of Z.
If array-like, draw contour lines at the specified levels. The values must be in increasing order.
- Return type:
~.contour.QuadContourSet
- Parameters:
corner_mask (bool, default: contour.corner_mask) – Enable/disable corner masking, which only has an effect if Z is a masked array. If
False, any quad touching a masked point is masked out. IfTrue, only the triangular corners of quads nearest those points are always masked out, other triangular corners comprising three unmasked points are contoured as usual.colors (color or list of color, optional) –
The colors of the levels, i.e. the lines for .contour and the areas for .contourf.
The sequence is cycled for the levels in ascending order. If the sequence is shorter than the number of levels, it’s repeated.
As a shortcut, a single color may be used in place of one-element lists, i.e.
'red'instead of['red']to color all levels with the same color.Changed in version 3.10: Previously a single color had to be expressed as a string, but now any valid color format may be passed.
By default (value None), the colormap specified by cmap will be used.
alpha (float, default: 1) – The alpha blending value, between 0 (transparent) and 1 (opaque).
cmap (str or ~matplotlib.colors.Colormap, default: image.cmap) –
The Colormap instance or registered colormap name used to map scalar data to colors.
This parameter is ignored if colors is set.
norm (str or ~matplotlib.colors.Normalize, optional) –
The normalization method used to scale scalar data to the [0, 1] range before mapping to colors using cmap. By default, a linear scaling is used, mapping the lowest value to 0 and the highest to 1.
If given, this can be one of the following:
An instance of .Normalize or one of its subclasses (see Colormap normalization).
A scale name, i.e. one of “linear”, “log”, “symlog”, “logit”, etc. For a list of available scales, call matplotlib.scale.get_scale_names(). In that case, a suitable .Normalize subclass is dynamically generated and instantiated.
This parameter is ignored if colors is set.
vmin (float, optional) –
When using scalar data and no explicit norm, vmin and vmax define the data range that the colormap covers. By default, the colormap covers the complete value range of the supplied data. It is an error to use vmin/vmax when a norm instance is given (but using a str norm name together with vmin/vmax is acceptable).
If vmin or vmax are not given, the default color scaling is based on levels.
This parameter is ignored if colors is set.
vmax (float, optional) –
When using scalar data and no explicit norm, vmin and vmax define the data range that the colormap covers. By default, the colormap covers the complete value range of the supplied data. It is an error to use vmin/vmax when a norm instance is given (but using a str norm name together with vmin/vmax is acceptable).
If vmin or vmax are not given, the default color scaling is based on levels.
This parameter is ignored if colors is set.
colorizer (~matplotlib.colorizer.Colorizer or None, default: None) –
The Colorizer object used to map color to data. If None, a Colorizer object is created from a norm and cmap.
This parameter is ignored if colors is set.
origin ({None, ‘upper’, ‘lower’, ‘image’}, default: None) –
Determines the orientation and exact position of Z by specifying the position of
Z[0, 0]. This is only relevant, if X, Y are not given.None:
Z[0, 0]is at X=0, Y=0 in the lower left corner.’lower’:
Z[0, 0]is at X=0.5, Y=0.5 in the lower left corner.’upper’:
Z[0, 0]is at X=N+0.5, Y=0.5 in the upper left corner.’image’: Use the value from image.origin.
extent ((x0, x1, y0, y1), optional) –
If origin is not None, then extent is interpreted as in .imshow: it gives the outer pixel boundaries. In this case, the position of Z[0, 0] is the center of the pixel, not a corner. If origin is None, then (x0, y0) is the position of Z[0, 0], and (x1, y1) is the position of Z[-1, -1].
This argument is ignored if X and Y are specified in the call to contour.
locator (ticker.Locator subclass, optional) – The locator is used to determine the contour levels if they are not given explicitly via levels. Defaults to ~.ticker.MaxNLocator.
extend ({'neither', 'both', 'min', 'max'}, default: 'neither') –
Determines the
contourf-coloring of values that are outside the levels range.If ‘neither’, values outside the levels range are not colored. If ‘min’, ‘max’ or ‘both’, color the values below, above or below and above the levels range.
Values below
min(levels)and abovemax(levels)are mapped to the under/over values of the .Colormap. Note that most colormaps do not have dedicated colors for these by default, so that the over and under values are the edge values of the colormap. You may want to set these values explicitly using .Colormap.set_under and .Colormap.set_over.Note
An existing .QuadContourSet does not get notified if properties of its colormap are changed. Therefore, an explicit call ~.ContourSet.changed() is needed after modifying the colormap. The explicit call can be left out, if a colorbar is assigned to the .QuadContourSet because it internally calls ~.ContourSet.changed().
Example:
x = np.arange(1, 10) y = x.reshape(-1, 1) h = x * y cs = plt.contourf(h, levels=[10, 30, 50], colors=['#808080', '#A0A0A0', '#C0C0C0'], extend='both') cs.cmap.set_over('red') cs.cmap.set_under('blue') cs.changed()
xunits (registered units, optional) – Override axis units by specifying an instance of a
matplotlib.units.ConversionInterface.yunits (registered units, optional) – Override axis units by specifying an instance of a
matplotlib.units.ConversionInterface.antialiased (bool, optional) – Enable antialiasing, overriding the defaults. For filled contours, the default is False. For line contours, it is taken from lines.antialiased.
nchunk (int >= 0, optional) – If 0, no subdivision of the domain. Specify a positive integer to divide the domain into subdomains of nchunk by nchunk quads. Chunking reduces the maximum length of polygons generated by the contouring algorithm which reduces the rendering workload passed on to the backend and also requires slightly less RAM. It can however introduce rendering artifacts at chunk boundaries depending on the backend, the antialiased flag and value of alpha.
linewidths (float or array-like, default: contour.linewidth) –
Only applies to .contour.
The line width of the contour lines.
If a number, all levels will be plotted with this linewidth.
If a sequence, the levels in ascending order will be plotted with the linewidths in the order specified.
If None, this falls back to lines.linewidth.
linestyles ({None, ‘solid’, ‘dashed’, ‘dashdot’, ‘dotted’}, optional) –
Only applies to .contour.
If linestyles is None, the default is ‘solid’ unless the lines are monochrome. In that case, negative contours will instead take their linestyle from the negative_linestyles argument.
linestyles can also be an iterable of the above strings specifying a set of linestyles to be used. If this iterable is shorter than the number of contour levels it will be repeated as necessary.
negative_linestyles ({None, ‘solid’, ‘dashed’, ‘dashdot’, ‘dotted’}, optional) –
Only applies to .contour.
If linestyles is None and the lines are monochrome, this argument specifies the line style for negative contours.
If negative_linestyles is None, the default is taken from contour.negative_linestyle.
negative_linestyles can also be an iterable of the above strings specifying a set of linestyles to be used. If this iterable is shorter than the number of contour levels it will be repeated as necessary.
hatches (list[str], optional) –
Only applies to .contourf.
A list of cross hatch patterns to use on the filled areas. If None, no hatching will be added to the contour.
algorithm ({'mpl2005', 'mpl2014', 'serial', 'threaded'}, optional) –
Which contouring algorithm to use to calculate the contour lines and polygons. The algorithms are implemented in ContourPy, consult the ContourPy documentation for further information.
The default is taken from contour.algorithm.
clip_path (~matplotlib.patches.Patch or .Path or .TransformedPath) –
Set the clip path. See ~matplotlib.artist.Artist.set_clip_path.
Added in version 3.8.
data (indexable object, optional) – If given, all parameters also accept a string
s, which is interpreted asdata[s]ifsis a key indata.
Notes
Note
This is the pyplot wrapper for .axes.Axes.contourf.
.contourf differs from the MATLAB version in that it does not draw the polygon edges. To draw edges, add line contours with calls to .contour.
.contourf fills intervals that are closed at the top; that is, for boundaries z1 and z2, the filled region is:
z1 < Z <= z2
except for the lowest interval, which is closed on both sides (i.e. it includes the lowest value).
.contour and .contourf use a marching squares algorithm to compute contour locations. More information can be found in ContourPy documentation.
- morph(new_z, duration, delay=0, easing=None, persistent=True, **kwargs)[source]¶
Morph between the base dataset and a new dataset.
- Parameters:
new_x (array-like or float) – the x data points to morph to.
new_y (array-like or float) – the y data points to morph to.
duration (float) – the number of frames the animation runs from.
delay (float, default=0) – the number of frames after what the animation starts playing.
easing (callable, optional) – the easing used for this animation. If None, a linear easing is applied.
persistent (bool, default=True) – if True, the plot object will continue to be plotted after its last animation has played.
hist()) (For plot objects that take 1D datasets (e.g.)
new_x. (morph() only accepts)
- class diplotocus.animations.text(x, y, string, easing=None, axis=None, *args, **kwargs)[source]¶
Add text to the Axes.
Add the text s to the Axes at location x, y in data coordinates, with a default
horizontalalignmenton theleftandverticalalignmentat thebaseline.- Parameters:
x (float) – The position to place the text. By default, this is in data coordinates. The coordinate system can be changed using the transform parameter.
y (float) – The position to place the text. By default, this is in data coordinates. The coordinate system can be changed using the transform parameter.
duration (float) – Duration of the animation
delay (float, default=0) – Delay before starting
easing (callable, optional) – Easing function
axis (matplotlib.axes.Axes, optional) – Axis to plot on
- sstr
The text.
fontdict : dict, default: None
Discouraged
The use of fontdict is discouraged. Parameters should be passed as individual keyword arguments or using dictionary-unpacking
text(..., **fontdict).A dictionary to override the default text properties. If fontdict is None, the defaults are determined by .rcParams.
- Returns:
The created .Text instance.
- Return type:
.Text
- Parameters:
**kwargs (~matplotlib.text.Text properties.) –
Other miscellaneous text parameters.
Properties: agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: float or None animated: bool antialiased: bool backgroundcolor: color bbox: dict with properties for .patches.FancyBboxPatch clip_box: unknown clip_on: unknown clip_path: unknown color or c: color figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure fontfamily or family or fontname: {FONTNAME, ‘serif’, ‘sans-serif’, ‘cursive’, ‘fantasy’, ‘monospace’} fontproperties or font or font_properties: .font_manager.FontProperties or str or pathlib.Path fontsize or size: float or {‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’, ‘xx-large’} fontstretch or stretch: {a numeric value in range 0-1000, ‘ultra-condensed’, ‘extra-condensed’, ‘condensed’, ‘semi-condensed’, ‘normal’, ‘semi-expanded’, ‘expanded’, ‘extra-expanded’, ‘ultra-expanded’} fontstyle or style: {‘normal’, ‘italic’, ‘oblique’} fontvariant or variant: {‘normal’, ‘small-caps’} fontweight or weight: {a numeric value in range 0-1000, ‘ultralight’, ‘light’, ‘normal’, ‘regular’, ‘book’, ‘medium’, ‘roman’, ‘semibold’, ‘demibold’, ‘demi’, ‘bold’, ‘heavy’, ‘extra bold’, ‘black’} gid: str horizontalalignment or ha: {‘left’, ‘center’, ‘right’} in_layout: bool label: object linespacing: float (multiple of font size) math_fontfamily: str mouseover: bool multialignment or ma: {‘left’, ‘right’, ‘center’} parse_math: bool path_effects: list of .AbstractPathEffect picker: None or bool or float or callable position: (float, float) rasterized: bool rotation: float or {‘vertical’, ‘horizontal’} rotation_mode: {None, ‘default’, ‘anchor’} sketch_params: (scale: float, length: float, randomness: float) snap: bool or None text: object transform: ~matplotlib.transforms.Transform transform_rotates_text: bool url: str usetex: bool, default: text.usetex verticalalignment or va: {‘baseline’, ‘bottom’, ‘center’, ‘center_baseline’, ‘top’} visible: bool wrap: bool x: float y: float zorder: float
Notes
Note
This is the pyplot wrapper for .axes.Axes.text.
Examples
Individual keyword arguments can be used to override any given parameter:
>>> text(x, y, s, fontsize=12)
The default transform specifies that text is in data coords, alternatively, you can specify text in axis coords ((0, 0) is lower-left and (1, 1) is upper-right). The example below places text in the center of the Axes:
>>> text(0.5, 0.5, 'matplotlib', horizontalalignment='center', ... verticalalignment='center', transform=ax.transAxes)
You can put a rectangular box around the text instance (e.g., to set a background color) by using the keyword bbox. bbox is a dictionary of ~matplotlib.patches.Rectangle properties. For example:
>>> text(x, y, s, bbox=dict(facecolor='red', alpha=0.5))
- class diplotocus.animations.svg(data, fc=None, ec='k', lw=2, easing=None, axis=None, *args, **kwargs)[source]¶
A vector SVG object.
- Parameters:
data (str) – SVG object as a string.
fc (color, default=None) – the face color.
ec (color, default='k') – the edge color.
lw (float, default=2) – the line width.
Easings¶
GUI¶
- class diplotocus.GUI.server.GUI(timeline=None, plot_objects=None, min_tracks=3, host='localhost', port=8008, open_browser=True)[source]¶
Bases:
objectA Graphical User Interface object that launches a python server that serves a webpage.
- Parameters:
timeline (Timeline) – the Timeline object that renders our animation.
plot_objects (list[dict]) –
- a list of dictionaries containing the keys:
name: the display name shown in the GUI.
object: the plot object.
- new_x/new_y (optional): datapoints to be used when the
morph() animation is used on the plot object.
min_tracks (
int) – the minimum number of tracks to be shown. This will be the initial number of tracks.host (
str) – the URL to which the server serves content.port (
int) – the port used to communicate with the server.open_browser (
bool) – if True, opens the webpage at host:port immediatly after the server is launched.