Place a legend on the Axes.
Call signatures:
The call signatures correspond to the following different ways to use this method:
1. Automatic detection of elements to be shown in the legend
The elements to be added to the legend are automatically determined, when you do not pass in any extra arguments.
In this case, the labels are taken from the artist. You can specify them either at artist creation or by calling the set_label() method on the artist:
or:
Specific lines can be excluded from the automatic legend element selection by defining a label starting with an underscore. This is default for all artists, so calling Axes.legend without any arguments and without setting the labels manually will result in no legend being drawn.
2. Explicitly listing the artists and labels in the legend
For full control of which artists have a legend entry, it is possible to pass an iterable of legend artists followed by an iterable of legend labels respectively:
3. Explicitly listing the artists in the legend
This is similar to 2, but the labels are taken from the artists' label properties. Example:
4. Labeling existing plot elements
Discouraged
This call signature is discouraged, because the relation between plot elements and labels is only implicit by their order and can easily be mixed up.
To make a legend for all artists on an Axes, call this function with an iterable of strings, one for each legend item. For example:
A list of Artists (lines, patches) to be added to the legend. Use this together with labels, if you need full control on what is shown in the legend and the automatic mechanism described above is not sufficient.
The length of handles and labels should be the same in this case. If they are not, they are truncated to the smaller length.
A list of labels to show next to the artists. Use this together with handles, if you need full control on what is shown in the legend and the automatic mechanism described above is not sufficient.
The location of the legend.
The strings 'upper left', 'upper right', 'lower left', 'lower right' place the legend at the corresponding corner of the axes/figure.
The strings 'upper center', 'lower center', 'center left', 'center right' place the legend at the center of the corresponding edge of the axes/figure.
The string 'center' places the legend at the center of the axes/figure.
The string 'best' places the legend at the location, among the nine locations defined so far, with the minimum overlap with other drawn artists. This option can be quite slow for plots with large amounts of data; your plotting speed may benefit from providing a specific location.
The location can also be a 2-tuple giving the coordinates of the lower-left corner of the legend in axes coordinates (in which case bbox_to_anchor will be ignored).
For back-compatibility, 'center right' (but no other location) can also be spelled 'right', and each "string" locations can also be given as a numeric value:
Location String
Location Code
'best'
0
'upper right'
1
'upper left'
2
'lower left'
3
'lower right'
4
'right'
5
'center left'
6
'center right'
7
'lower center'
8
'upper center'
9
'center'
10
Box that is used to position the legend in conjunction with loc. Defaults to axes.bbox (if called as a method to Axes.legend) or figure.bbox (if Figure.legend). This argument allows arbitrary placement of the legend.
Bbox coordinates are interpreted in the coordinate system given by bbox_transform, with the default transform Axes or Figure coordinates, depending on which legend is called.
If a 4-tuple or BboxBase is given, then it specifies the bbox (x, y, width, height) that the legend is placed in. To put the legend in the best location in the bottom right quadrant of the axes (or figure):
A 2-tuple (x, y) places the corner of the legend specified by loc at x, y. For example, to put the legend's upper right-hand corner in the center of the axes (or figure) the following keywords can be used:
The number of columns that the legend has.
The font properties of the legend. If None (default), the current matplotlib.rcParams will be used.
The font size of the legend. If the value is numeric the size will be the absolute font size in points. String values are relative to the current default font size. This argument is only used if prop is not specified.
The color of the text in the legend. Either a valid color string (for example, 'red'), or a list of color strings. The labelcolor can also be made to match the color of the line or marker using 'linecolor', 'markerfacecolor' (or 'mfc'), or 'markeredgecolor' (or 'mec').
Labelcolor can be set globally using rcParams["legend.labelcolor"] (default: 'None'). If None, use rcParams["text.color"] (default: 'black').
The number of marker points in the legend when creating a legend entry for a Line2D (line).
The number of marker points in the legend when creating a legend entry for a PathCollection (scatter plot).
The vertical offset (relative to the font size) for the markers created for a scatter plot legend entry. 0.0 is at the base the legend text, and 1.0 is at the top. To draw all markers at the same height, set to [0.5].
The relative size of legend markers compared with the originally drawn ones.
If True, legend marker is placed to the left of the legend label. If False, legend marker is placed to the right of the legend label.
Whether the legend should be drawn on a patch (frame).
Whether round edges should be enabled around the FancyBboxPatch which makes up the legend's background.
Whether to draw a shadow behind the legend.
The alpha transparency of the legend's background. If shadow is activated and framealpha is None, the default value is ignored.
The legend's background color. If "inherit", use rcParams["axes.facecolor"] (default: 'white').
The legend's background patch edge color. If "inherit", use take rcParams["axes.edgecolor"] (default: 'black').
If mode is set to "expand" the legend will be horizontally expanded to fill the axes area (or bbox_to_anchor if defines the legend's size).
The transform for the bounding box (bbox_to_anchor). For a value of None (default) the Axes' transAxes transform will be used.
The legend's title. Default is no title (None).
The font properties of the legend's title. If None (default), the title_fontsize argument will be used if present; if title_fontsize is also None, the current rcParams["legend.title_fontsize"] (default: None) will be used.
The font size of the legend's title. Note: This cannot be combined with title_fontproperties. If you want to set the fontsize alongside other font properties, use the size parameter in title_fontproperties.
The fractional whitespace inside the legend border, in font-size units.
The vertical space between the legend entries, in font-size units.
The length of the legend handles, in font-size units.
The height of the legend handles, in font-size units.
The pad between the legend handle and text, in font-size units.
The pad between the axes and legend border, in font-size units.
The spacing between columns, in font-size units.
The custom dictionary mapping instances or types to a legend handler. This handler_map updates the default handler map found at matplotlib.legend.Legend.get_legend_handler_map.
See also
Some artists are not supported by this function. See Legend guide for details.
(Source code, png, pdf)
Errorbar limit selection
Plotting masked and NaN values
Scatter Symbol
Stairs Demo
Step Demo
Infinite lines
Parasite Simple
Findobj Demo
Zorder Demo
The Sankey class
SVG Histogram
Basic Usage
Legend guide


Control behavior of major tick locators.
Because the locator is involved in autoscaling, autoscale_view is called automatically after the parameters are changed.
The axis on which to operate.
Parameter passed to autoscale_view. Default is None, for no change.
Remaining keyword arguments are passed to directly to the set_params() method of the locator. Supported keywords depend on the type of the locator. See for example set_params for the ticker.MaxNLocator used by default for linear axes.
When plotting small subplots, one might want to reduce the maximum number of ticks and use tight bounds, for example:


Make a plot with log scaling on both the x and y axis.
Call signatures:
This is just a thin wrapper around plot which additionally changes both the x-axis and the y-axis to log scaling. All of the concepts and parameters of plot can be used here as well.
The additional parameters base, subs and nonpositive control the x/y-axis properties. They are just forwarded to Axes.set_xscale and Axes.set_yscale. To use different properties on the x-axis and the y-axis, use e.g. ax.set_xscale("log", base=10); ax.set_yscale("log", base=2).
Base of the logarithm.
The location of the minor ticks. If None, reasonable locations are automatically chosen depending on the number of decades in the plot. See Axes.set_xscale/Axes.set_yscale for details.
Non-positive values can be masked as invalid, or clipped to a very small positive number.
All parameters supported by plot.
Objects representing the plotted data.


Set the colormap to 'magma'.
This changes the default colormap as well as the colormap of the current image if there is one. See help(colormaps) for more information.


Plot the magnitude spectrum.
Compute the magnitude spectrum of x. Data is padded to a length of pad_to and the windowing function window is applied to the signal.
Array or sequence containing the data.
The sampling frequency (samples per time unit). It is used to calculate the Fourier frequencies, freqs, in cycles per time unit.
A function or a vector of length NFFT. To create window vectors see window_hanning, window_none, numpy.blackman, numpy.hamming, numpy.bartlett, scipy.signal, scipy.signal.get_window, etc. If a function is passed as the argument, it must take a data segment as an argument and return the windowed version of the segment.
Which sides of the spectrum to return. 'default' is one-sided for real data and two-sided for complex data. 'onesided' forces the return of a one-sided spectrum, while 'twosided' forces two-sided.
The number of points to which the data segment is padded when performing the FFT. While not increasing the actual resolution of the spectrum (the minimum distance between resolvable peaks), this can give more points in the plot, allowing for more detail. This corresponds to the n parameter in the call to fft(). The default is None, which sets pad_to equal to the length of the input signal (i.e. no padding).
The scaling of the values in the spec. 'linear' is no scaling. 'dB' returns the values in dB scale, i.e., the dB amplitude (20 * log10). 'default' is 'linear'.
The center frequency of x, which offsets the x extents of the plot to reflect the frequency range used when a signal is acquired and then filtered and downsampled to baseband.
The values for the magnitude spectrum before scaling (real valued).
The frequencies corresponding to the elements in spectrum.
The line created by this function.
If given, the following parameters also accept a string s, which is interpreted as data[s] (unless this raises an exception):
x
Keyword arguments control the Line2D properties:
Property
Description
agg_filter
a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha
scalar or None
animated
bool
antialiased or aa
bool
clip_box
Bbox
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
Figure
fillstyle
{'full', 'left', 'right', 'bottom', 'top', 'none'}
gid
str
in_layout
bool
label
object
linestyle or ls
{'-', '--', '-.', ':', '', (offset, on-off-seq), ...}
linewidth or lw
float
marker
marker style string, Path or 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]
path_effects
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
Plots the power spectral density.
Plots the angles of the corresponding frequencies.
Plots the phase (unwrapped angle) of the corresponding frequencies.
Can plot the magnitude spectrum of segments within the signal in a colormap.


Set or retrieve autoscaling margins.
The padding added to each limit of the Axes is the margin times the data interval. All input parameters must be floats within the range [0, 1]. Passing both positional and keyword arguments is invalid and will raise a TypeError. If no arguments (positional or otherwise) are provided, the current margins will remain in place and simply be returned.
Specifying any margin changes only the autoscaling; for example, if xmargin is not None, then xmargin times the X data interval will be added to each end of that interval before it is used in autoscaling.
If a single positional argument is provided, it specifies both margins of the x-axis and y-axis limits. If two positional arguments are provided, they will be interpreted as xmargin, ymargin. If setting the margin on a single axis is desired, use the keyword arguments described below.
Specific margin values for the x-axis and y-axis, respectively. These cannot be used with positional arguments, but can be used individually to alter on e.g., only the y-axis.
The tight parameter is passed to autoscale_view(), which is executed after a margin is changed; the default here is True, on the assumption that when margins are specified, no additional padding to match tick marks is usually desired. Set tight to None will preserve the previous setting.
If a previously used Axes method such as pcolor() has set use_sticky_edges to True, only the limits not set by the "sticky artists" will be modified. To force all of the margins to be set, set use_sticky_edges to False before calling margins().
Rotating custom tick labels


Display an array as a matrix in a new figure window.
The origin is set at the upper left hand corner and rows (first dimension of the array) are displayed horizontally. The aspect ratio of the figure window is that of the array, unless this would make an excessively short or narrow figure.
Tick labels for the xaxis are placed on top.
The matrix to be displayed.
If None, create a new figure window with automatic numbering.
If a nonzero integer, draw into the figure with the given number (create it if it does not exist).
If 0, use the current axes (or create one if it does not exist).
Note
Because of how Axes.matshow tries to set the figure aspect ratio to be the one of the array, strange things may happen if you reuse an existing figure.
Matshow


Display minor ticks on the Axes.
Displaying minor ticks may reduce performance; you may turn them off using minorticks_off() if drawing speed is a problem.


Set the colormap to 'nipy_spectral'.
This changes the default colormap as well as the colormap of the current image if there is one. See help(colormaps) for more information.


Run the GUI event loop for interval seconds.
If there is an active figure, it will be updated and displayed before the pause, and the GUI event loop (if any) will run during the pause.
This can be used for crude animation. For more complex animation use matplotlib.animation.
If there is no active figure, sleep for interval seconds instead.
See also
Proper animations
Show all figures and optional block until all figures are closed.
pyplot animation
Rotating a 3D plot
Rotating 3D wireframe plot
Faster rendering by using blitting


Create a pseudocolor plot with a non-regular rectangular grid.
Call signature:
X and Y can be used to specify the corners of the quadrilaterals.
Hint
pcolor() can be very slow for large arrays. In most cases you should use the similar but much faster pcolormesh instead. See Differences between pcolor() and pcolormesh() for a discussion of the differences.
The color-mapped values.
The coordinates of the corners of quadrilaterals of a pcolormesh:
Note that the column index corresponds to the x-coordinate, and the row index corresponds to y. For details, see the Notes section below.
If shading='flat' the dimensions of X and Y should be one greater than those of C, and the quadrilateral is colored due to the value at C[i, j]. If X, Y and C have equal dimensions, a warning will be raised and the last row and column of C will be ignored.
If shading='nearest', the dimensions of X and Y should be the same as those of C (if not, a ValueError will be raised). The color C[i, j] will be centered on (X[i, j], Y[i, j]).
If X and/or Y are 1-D arrays or column vectors they will be expanded as needed into the appropriate 2D arrays, making a rectangular grid.
The fill style for the quadrilateral. Possible values:
See pcolormesh grids and shading for more description.
A Colormap instance or registered colormap name. The colormap maps the C values to colors.
The Normalize instance scales the data values to the canonical colormap range [0, 1] for mapping to colors. By default, the data range is mapped to the colorbar range using linear scaling.
The colorbar range. If None, suitable min/max values are automatically chosen by the Normalize instance (defaults to the respective min/max values of C in case of the default linear scaling). It is an error to use vmin/vmax when norm is given.
The color of the edges. Defaults to 'none'. Possible values:
The singular form edgecolor works as an alias.
The alpha blending value of the face color, between 0 (transparent) and 1 (opaque). Note: The edgecolor is currently not affected by this.
Whether to snap the mesh to pixel boundaries.
The default antialiaseds is False if the default edgecolors="none" is used. This eliminates artificial lines at patch boundaries, and works regardless of the value of alpha. If edgecolors is not "none", then the default antialiaseds is taken from rcParams["patch.antialiased"] (default: True). Stroking the edges may be preferred if alpha is 1, but will cause artifacts otherwise.
If given, all parameters also accept a string s, which is interpreted as data[s] (unless this raises an exception).
Additionally, the following arguments are allowed. They are passed along to the PolyCollection constructor:
Property
Description
agg_filter
a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha
array-like or scalar 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
Bbox
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 colors or 'face'
facecolor or facecolors or fc
color or list of colors
figure
Figure
gid
str
hatch
{'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
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
norm
Normalize or None
offset_transform
Transform
offsets
(N, 2) or (2,) array-like
path_effects
AbstractPathEffect
paths
list of array-like
picker
None or bool or float or callable
pickradius
float
rasterized
bool
sizes
ndarray or None
sketch_params
(scale: float, length: float, randomness: float)
snap
bool or None
transform
Transform
url
str
urls
list of str or None
verts
list of array-like
verts_and_codes
unknown
visible
bool
zorder
float
See also
for an explanation of the differences between pcolor and pcolormesh.
If X and Y are each equidistant, imshow can be a faster alternative.
Masked arrays
X, Y and C may be masked arrays. If either C[i, j], or one of the vertices surrounding C[i, j] (X or Y at [i, j], [i+1, j], [i, j+1], [i+1, j+1]) is masked, nothing is plotted.
Grid orientation
The grid orientation follows the standard matrix convention: An array C with shape (nrows, ncolumns) is plotted with the column number as X and the row number as Y.


Create a pseudocolor plot with a non-regular rectangular grid.
Call signature:
X and Y can be used to specify the corners of the quadrilaterals.
Hint
pcolormesh is similar to pcolor. It is much faster and preferred in most cases. For a detailed discussion on the differences see Differences between pcolor() and pcolormesh().
The color-mapped values.
The coordinates of the corners of quadrilaterals of a pcolormesh:
Note that the column index corresponds to the x-coordinate, and the row index corresponds to y. For details, see the Notes section below.
If shading='flat' the dimensions of X and Y should be one greater than those of C, and the quadrilateral is colored due to the value at C[i, j]. If X, Y and C have equal dimensions, a warning will be raised and the last row and column of C will be ignored.
If shading='nearest' or 'gouraud', the dimensions of X and Y should be the same as those of C (if not, a ValueError will be raised). For 'nearest' the color C[i, j] is centered on (X[i, j], Y[i, j]). For 'gouraud', a smooth interpolation is caried out between the quadrilateral corners.
If X and/or Y are 1-D arrays or column vectors they will be expanded as needed into the appropriate 2D arrays, making a rectangular grid.
A Colormap instance or registered colormap name. The colormap maps the C values to colors.
The Normalize instance scales the data values to the canonical colormap range [0, 1] for mapping to colors. By default, the data range is mapped to the colorbar range using linear scaling.
The colorbar range. If None, suitable min/max values are automatically chosen by the Normalize instance (defaults to the respective min/max values of C in case of the default linear scaling). It is an error to use vmin/vmax when norm is given.
The color of the edges. Defaults to 'none'. Possible values:
The singular form edgecolor works as an alias.
The alpha blending value, between 0 (transparent) and 1 (opaque).
The fill style for the quadrilateral; defaults to 'flat' or rcParams["pcolor.shading"] (default: 'auto'). Possible values:
See pcolormesh grids and shading for more description.
Whether to snap the mesh to pixel boundaries.
Rasterize the pcolormesh when drawing vector graphics. This can speed up rendering and produce smaller files for large data sets. See also Rasterization for vector graphics.
If given, all parameters also accept a string s, which is interpreted as data[s] (unless this raises an exception).
Additionally, the following arguments are allowed. They are passed along to the QuadMesh constructor:
Property
Description
agg_filter
a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha
array-like or scalar or None
animated
bool
antialiased or aa or antialiaseds
bool or list of bools
array
(M, N) array-like or M*N array-like
capstyle
CapStyle or {'butt', 'projecting', 'round'}
clim
(vmin: float, vmax: float)
clip_box
Bbox
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 colors or 'face'
facecolor or facecolors or fc
color or list of colors
figure
Figure
gid
str
hatch
{'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
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
norm
Normalize or None
offset_transform
Transform
offsets
(N, 2) or (2,) array-like
path_effects
AbstractPathEffect
picker
None or bool or float or callable
pickradius
float
rasterized
bool
sketch_params
(scale: float, length: float, randomness: float)
snap
bool or None
transform
Transform
url
str
urls
list of str or None
visible
bool
zorder
float
See also
An alternative implementation with slightly different features. For a detailed discussion on the differences see Differences between pcolor() and pcolormesh().
If X and Y are each equidistant, imshow can be a faster alternative.
Masked arrays
C may be a masked array. If C[i, j] is masked, the corresponding quadrilateral will be transparent. Masking of X and Y is not supported. Use pcolor if you need this functionality.
Grid orientation
The grid orientation follows the standard matrix convention: An array C with shape (nrows, ncolumns) is plotted with the column number as X and the row number as Y.
Differences between pcolor() and pcolormesh()
Both methods are used to create a pseudocolor plot of a 2D array using quadrilaterals.
The main difference lies in the created object and internal data handling: While pcolor returns a PolyCollection, pcolormesh returns a QuadMesh. The latter is more specialized for the given purpose and thus is faster. It should almost always be preferred.
There is also a slight difference in the handling of masked arrays. Both pcolor and pcolormesh support masked arrays for C. However, only pcolor supports masked arrays for X and Y. The reason lies in the internal handling of the masked values. pcolor leaves out the respective polygons from the PolyCollection. pcolormesh sets the facecolor of the masked elements to transparent. You can see the difference when using edgecolors. While all edges are drawn irrespective of masking in a QuadMesh, the edge between two adjacent masked quadrilaterals in pcolor is not drawn as the corresponding polygons do not exist in the PolyCollection.
Another difference is the support of Gouraud shading in pcolormesh, which is not available with pcolor.


Plot the phase spectrum.
Compute the phase spectrum (unwrapped angle spectrum) of x. Data is padded to a length of pad_to and the windowing function window is applied to the signal.
Array or sequence containing the data
The sampling frequency (samples per time unit). It is used to calculate the Fourier frequencies, freqs, in cycles per time unit.
A function or a vector of length NFFT. To create window vectors see window_hanning, window_none, numpy.blackman, numpy.hamming, numpy.bartlett, scipy.signal, scipy.signal.get_window, etc. If a function is passed as the argument, it must take a data segment as an argument and return the windowed version of the segment.
Which sides of the spectrum to return. 'default' is one-sided for real data and two-sided for complex data. 'onesided' forces the return of a one-sided spectrum, while 'twosided' forces two-sided.
The number of points to which the data segment is padded when performing the FFT. While not increasing the actual resolution of the spectrum (the minimum distance between resolvable peaks), this can give more points in the plot, allowing for more detail. This corresponds to the n parameter in the call to fft(). The default is None, which sets pad_to equal to the length of the input signal (i.e. no padding).
The center frequency of x, which offsets the x extents of the plot to reflect the frequency range used when a signal is acquired and then filtered and downsampled to baseband.
The values for the phase spectrum in radians (real valued).
The frequencies corresponding to the elements in spectrum.
The line created by this function.
If given, the following parameters also accept a string s, which is interpreted as data[s] (unless this raises an exception):
x
Keyword arguments control the Line2D properties:
Property
Description
agg_filter
a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha
scalar or None
animated
bool
antialiased or aa
bool
clip_box
Bbox
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
Figure
fillstyle
{'full', 'left', 'right', 'bottom', 'top', 'none'}
gid
str
in_layout
bool
label
object
linestyle or ls
{'-', '--', '-.', ':', '', (offset, on-off-seq), ...}
linewidth or lw
float
marker
marker style string, Path or 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]
path_effects
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
Plots the magnitudes of the corresponding frequencies.
Plots the wrapped version of this function.
Can plot the phase spectrum of segments within the signal in a colormap.


Plot a pie chart.
Make a pie chart of array x. The fractional area of each wedge is given by x/sum(x). If sum(x) < 1, then the values of x give the fractional area directly and the array will not be normalized. The resulting pie will have an empty wedge of size 1 - sum(x).
The wedges are plotted counterclockwise, by default starting from the x-axis.
The wedge sizes.
If not None, is a len(x) array which specifies the fraction of the radius with which to offset each wedge.
A sequence of strings providing the labels for each wedge
A sequence of colors through which the pie chart will cycle. If None, will use the colors in the currently active cycle.
If not None, is a string or function used to label the wedges with their numeric value. The label will be placed inside the wedge. If it is a format string, the label will be fmt % pct. If it is a function, it will be called.
The ratio between the center of each pie slice and the start of the text generated by autopct. Ignored if autopct is None.
Draw a shadow beneath the pie.
When True, always make a full pie by normalizing x so that sum(x) == 1. False makes a partial pie if sum(x) <= 1 and raises a ValueError for sum(x) > 1.
The radial distance at which the pie labels are drawn. If set to None, label are not drawn, but are stored for use in legend()
The angle by which the start of the pie is rotated, counterclockwise from the x-axis.
The radius of the pie.
Specify fractions direction, clockwise or counterclockwise.
Dict of arguments passed to the wedge objects making the pie. For example, you can pass in wedgeprops = {'linewidth': 3} to set the width of the wedge border lines equal to 3. For more details, look at the doc/arguments of the wedge object. By default clip_on=False.
Dict of arguments to pass to the text objects.
The coordinates of the center of the chart.
Plot Axes frame with the chart if true.
Rotate each label to the angle of the corresponding slice if true.
If given, the following parameters also accept a string s, which is interpreted as data[s] (unless this raises an exception):
x, explode, labels, colors
A sequence of matplotlib.patches.Wedge instances
A list of the label Text instances.
A list of Text instances for the numeric labels. This will only be returned if the parameter autopct is not None.
The pie chart will probably look best if the figure and Axes are square, or the Axes aspect is equal. This method sets the aspect ratio of the axis to "equal". The Axes aspect ratio can be controlled with Axes.set_aspect.


Set the colormap to 'pink'.
This changes the default colormap as well as the colormap of the current image if there is one. See help(colormaps) for more information.


Set the colormap to 'plasma'.
This changes the default colormap as well as the colormap of the current image if there is one. See help(colormaps) for more information.


Plot y versus x as lines and/or markers.
Call signatures:
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.
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:
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:
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:
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:
is equivalent to:
The third way is to specify multiple sets of [x], y, [fmt] groups:
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 rcParams["axes.prop_cycle"] (default: cycler('color', ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf'])).
The horizontal / vertical coordinates of the data points. x values are optional and default to range(len(y)).
Commonly, these parameters are 1D arrays.
They can also be scalars, or two-dimensional (in that case, the columns represent separate data sets).
These arguments cannot be passed as keywords.
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.
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 be plt(x, y) or plt(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 string plot('n', 'o', '', data=obj).
A list of lines representing the plotted data.
These parameters determine if the view limits are adapted to the data limits. The values are passed on to autoscale_view.
kwargs are used to specify properties like a line label (for auto legends), linewidth, antialiasing, marker face color. Example:
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:
Property
Description
agg_filter
a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha
scalar or None
animated
bool
antialiased or aa
bool
clip_box
Bbox
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
Figure
fillstyle
{'full', 'left', 'right', 'bottom', 'top', 'none'}
gid
str
in_layout
bool
label
object
linestyle or ls
{'-', '--', '-.', ':', '', (offset, on-off-seq), ...}
linewidth or lw
float
marker
marker style string, Path or 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]
path_effects
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
XY scatter plot with markers of varying size and/or color ( sometimes also called bubble chart).
Format Strings
A format string consists of a part for color, marker and line:
Each of them is optional. If not provided, the value from the style cycle is used. Exception: If line is given, but no marker, 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:
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').
Plotting masked and NaN values
Scatter Masked
Stairs Demo
Step Demo
Custom Figure subclasses
Managing multiple figures in pyplot
Shared Axis
Multiple subplots
Controlling style of text and labels using a dictionary
Title positioning
Infinite lines
plot() format string
Pyplot Mathtext
Pyplot Simple
Pyplot Three
Pyplot Two Subplots
Dolphins
Solarized Light stylesheet
Frame grabbing
Coords Report
Customize Rc
Findobj Demo
Multipage PDF
Print Stdout
Set and get properties
transforms.offset_copy
Zorder Demo
Custom scale
Placing date ticks using recurrence rules
Rotating custom tick labels
Tool Manager
Buttons
Slider
Snapping Sliders to Discrete Values
Basic Usage
Pyplot tutorial
Customizing Matplotlib with style sheets and rcParams
Path effects guide


Plot coercing the axis to treat floats as dates.
Discouraged
This method exists for historic reasons and will be deprecated in the future.
Similar to plot, this plots y vs. x as lines or markers. However, the axis labels are formatted as dates depending on xdate and ydate. Note that plot will work with datetime and numpy.datetime64 objects without resorting to this method.
The coordinates of the data points. If xdate or ydate is True, the respective values x or y are interpreted as Matplotlib dates.
The plot format string. For details, see the corresponding parameter in plot.
The time zone to use in labeling dates.
If True, the x-axis will be interpreted as Matplotlib dates.
If True, the y-axis will be interpreted as Matplotlib dates.
Objects representing the plotted data.
If given, the following parameters also accept a string s, which is interpreted as data[s] (unless this raises an exception):
x, y
Keyword arguments control the Line2D properties:
Property
Description
agg_filter
a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha
scalar or None
animated
bool
antialiased or aa
bool
clip_box
Bbox
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
Figure
fillstyle
{'full', 'left', 'right', 'bottom', 'top', 'none'}
gid
str
in_layout
bool
label
object
linestyle or ls
{'-', '--', '-.', ':', '', (offset, on-off-seq), ...}
linewidth or lw
float
marker
marker style string, Path or 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]
path_effects
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
Helper functions on dates.
Convert dates to num.
Convert num to dates.
Create an equally spaced sequence of dates.
If you are using custom date tickers and formatters, it may be necessary to set the formatters/locators after the call to plot_date. plot_date will set the default tick locator to AutoDateLocator (if the tick locator is not already set to a DateLocator instance) and the default tick formatter to AutoDateFormatter (if the tick formatter is not already set to a DateFormatter instance).


Function
Description
acorr
Plot the autocorrelation of x.
angle_spectrum
Plot the angle spectrum.
annotate
Annotate the point xy with text text.
arrow
Add an arrow to the Axes.
autoscale
Autoscale the axis view to the data (toggle).
axes
Add an axes to the current figure and make it the current axes.
axhline
Add a horizontal line across the axis.
axhspan
Add a horizontal span (rectangle) across the Axes.
axis
Convenience method to get or set some axis properties.
axline
Add an infinitely long straight line.
axvline
Add a vertical line across the Axes.
axvspan
Add a vertical span (rectangle) across the Axes.
bar
Make a bar plot.
bar_label
Label a bar plot.
barbs
Plot a 2D field of barbs.
barh
Make a horizontal bar plot.
box
Turn the axes box on or off on the current axes.
boxplot
Draw a box and whisker plot.
broken_barh
Plot a horizontal sequence of rectangles.
cla
Clear the current axes.
clabel
Label a contour plot.
clf
Clear the current figure.
clim
Set the color limits of the current image.
close
Close a figure window.
cohere
Plot the coherence between x and y.
colorbar
Add a colorbar to a plot.
contour
Plot contour lines.
contourf
Plot filled contours.
csd
Plot the cross-spectral density.
delaxes
Remove an Axes (defaulting to the current axes) from its figure.
draw
Redraw the current figure.
draw_if_interactive
Redraw the current figure if in interactive mode.
errorbar
Plot y versus x as lines and/or markers with attached errorbars.
eventplot
Plot identical parallel lines at the given positions.
figimage
Add a non-resampled image to the figure.
figlegend
Place a legend on the figure.
fignum_exists
Return whether the figure with the given id exists.
figtext
Add text to figure.
figure
Create a new figure, or activate an existing figure.
fill
Plot filled polygons.
fill_between
Fill the area between two horizontal curves.
fill_betweenx
Fill the area between two vertical curves.
findobj
Find artist objects.
gca
Get the current Axes.
gcf
Get the current figure.
gci
Get the current colorable artist.
get
Return the value of an Artist's property, or print all of them.
get_figlabels
Return a list of existing figure labels.
get_fignums
Return a list of existing figure numbers.
getp
Return the value of an Artist's property, or print all of them.
grid
Configure the grid lines.
hexbin
Make a 2D hexagonal binning plot of points x, y.
hist
Plot a histogram.
hist2d
Make a 2D histogram plot.
hlines
Plot horizontal lines at each y from xmin to xmax.
imread
Read an image from a file into an array.
imsave
Save an array as an image file.
imshow
Display data as an image, i.e., on a 2D regular raster.
install_repl_displayhook
Install a repl display hook so that any stale figure are automatically redrawn when control is returned to the repl.
ioff
Disable interactive mode.
ion
Enable interactive mode.
isinteractive
Return whether plots are updated after every plotting command.
legend
Place a legend on the Axes.
locator_params
Control behavior of major tick locators.
loglog
Make a plot with log scaling on both the x and y axis.
magnitude_spectrum
Plot the magnitude spectrum.
margins
Set or retrieve autoscaling margins.
matshow
Display an array as a matrix in a new figure window.
minorticks_off
Remove minor ticks from the Axes.
minorticks_on
Display minor ticks on the Axes.
new_figure_manager
Create a new figure manager instance.
pause
Run the GUI event loop for interval seconds.
pcolor
Create a pseudocolor plot with a non-regular rectangular grid.
pcolormesh
Create a pseudocolor plot with a non-regular rectangular grid.
phase_spectrum
Plot the phase spectrum.
pie
Plot a pie chart.
plot
Plot y versus x as lines and/or markers.
plot_date
Plot coercing the axis to treat floats as dates.
polar
Make a polar plot.
psd
Plot the power spectral density.
quiver
Plot a 2D field of arrows.
quiverkey
Add a key to a quiver plot.
rc
Set the current rcParams.
rc_context
Return a context manager for temporarily changing rcParams.
rcdefaults
Restore the rcParams from Matplotlib's internal default style.
rgrids
Get or set the radial gridlines on the current polar plot.
savefig
Save the current figure.
sca
Set the current Axes to ax and the current Figure to the parent of ax.
scatter
A scatter plot of y vs.
sci
Set the current image.
semilogx
Make a plot with log scaling on the x axis.
semilogy
Make a plot with log scaling on the y axis.
set_cmap
Set the default colormap, and applies it to the current image if any.
set_loglevel
Set Matplotlib's root logger and root logger handler level, creating the handler if it does not exist yet.
setp
Set one or more properties on an Artist, or list allowed values.
show
Display all open figures.
specgram
Plot a spectrogram.
spy
Plot the sparsity pattern of a 2D array.
stackplot
Draw a stacked area plot.
stairs
A stepwise constant function as a line with bounding edges or a filled plot.
stem
Create a stem plot.
step
Make a step plot.
streamplot
Draw streamlines of a vector flow.
subplot
Add an Axes to the current figure or retrieve an existing Axes.
subplot2grid
Create a subplot at a specific location inside a regular grid.
subplot_mosaic
Build a layout of Axes based on ASCII art or nested lists.
subplot_tool
Launch a subplot tool window for a figure.
subplots
Create a figure and a set of subplots.
subplots_adjust
Adjust the subplot layout parameters.
suptitle
Add a centered suptitle to the figure.
switch_backend
Close all open figures and set the Matplotlib backend.
table
Add a table to an Axes.
text
Add text to the Axes.
thetagrids
Get or set the theta gridlines on the current polar plot.
tick_params
Change the appearance of ticks, tick labels, and gridlines.
ticklabel_format
Configure the ScalarFormatter used by default for linear axes.
tight_layout
Adjust the padding between and around subplots.
title
Set a title for the Axes.
tricontour
Draw contour lines on an unstructured triangular grid.
tricontourf
Draw contour regions on an unstructured triangular grid.
tripcolor
Create a pseudocolor plot of an unstructured triangular grid.
triplot
Draw a unstructured triangular grid as lines and/or markers.
twinx
Make and return a second axes that shares the x-axis.
twiny
Make and return a second axes that shares the y-axis.
uninstall_repl_displayhook
Uninstall the Matplotlib display hook.
violinplot
Make a violin plot.
vlines
Plot vertical lines at each x from ymin to ymax.
xcorr
Plot the cross correlation between x and y.
xkcd
Turn on xkcd sketch-style drawing mode.
xlabel
Set the label for the x-axis.
xlim
Get or set the x limits of the current axes.
xscale
Set the x-axis scale.
xticks
Get or set the current tick locations and labels of the x-axis.
ylabel
Set the label for the y-axis.
ylim
Get or set the y-limits of the current axes.
yscale
Set the y-axis scale.
yticks
Get or set the current tick locations and labels of the y-axis.


Make a polar plot.
call signature:
Multiple theta, r arguments are supported, with format strings, as in plot.
transforms.offset_copy


Set the colormap to 'prism'.
This changes the default colormap as well as the colormap of the current image if there is one. See help(colormaps) for more information.


Plot the power spectral density.
The power spectral density \(P_{xx}\) by Welch's average periodogram method. The vector x is divided into NFFT length segments. Each segment is detrended by function detrend and windowed by function window. noverlap gives the length of the overlap between segments. The \(|\mathrm{fft}(i)|^2\) of each segment \(i\) are averaged to compute \(P_{xx}\), with a scaling to correct for power loss due to windowing.
If len(x) < NFFT, it will be zero padded to NFFT.
Array or sequence containing the data
The sampling frequency (samples per time unit). It is used to calculate the Fourier frequencies, freqs, in cycles per time unit.
A function or a vector of length NFFT. To create window vectors see window_hanning, window_none, numpy.blackman, numpy.hamming, numpy.bartlett, scipy.signal, scipy.signal.get_window, etc. If a function is passed as the argument, it must take a data segment as an argument and return the windowed version of the segment.
Which sides of the spectrum to return. 'default' is one-sided for real data and two-sided for complex data. 'onesided' forces the return of a one-sided spectrum, while 'twosided' forces two-sided.
The number of points to which the data segment is padded when performing the FFT. This can be different from NFFT, which specifies the number of data points used. While not increasing the actual resolution of the spectrum (the minimum distance between resolvable peaks), this can give more points in the plot, allowing for more detail. This corresponds to the n parameter in the call to fft(). The default is None, which sets pad_to equal to NFFT
The number of data points used in each block for the FFT. A power 2 is most efficient. This should NOT be used to get zero padding, or the scaling of the result will be incorrect; use pad_to for this instead.
The function applied to each segment before fft-ing, designed to remove the mean or linear trend. Unlike in MATLAB, where the detrend parameter is a vector, in Matplotlib it is a function. The mlab module defines detrend_none, detrend_mean, and detrend_linear, but you can use a custom function as well. You can also use a string to choose one of the functions: 'none' calls detrend_none. 'mean' calls detrend_mean. 'linear' calls detrend_linear.
Whether the resulting density values should be scaled by the scaling frequency, which gives density in units of Hz^-1. This allows for integration over the returned frequency values. The default is True for MATLAB compatibility.
The number of points of overlap between segments.
The center frequency of x, which offsets the x extents of the plot to reflect the frequency range used when a signal is acquired and then filtered and downsampled to baseband.
Whether to include the line object plotted in the returned values.
The values for the power spectrum \(P_{xx}\) before scaling (real valued).
The frequencies corresponding to the elements in Pxx.
The line created by this function. Only returned if return_line is True.
If given, the following parameters also accept a string s, which is interpreted as data[s] (unless this raises an exception):
x
Keyword arguments control the Line2D properties:
Property
Description
agg_filter
a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha
scalar or None
animated
bool
antialiased or aa
bool
clip_box
Bbox
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
Figure
fillstyle
{'full', 'left', 'right', 'bottom', 'top', 'none'}
gid
str
in_layout
bool
label
object
linestyle or ls
{'-', '--', '-.', ':', '', (offset, on-off-seq), ...}
linewidth or lw
float
marker
marker style string, Path or 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]
path_effects
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
Differs in the default overlap; in not returning the mean of the segment periodograms; in returning the times of the segments; and in plotting a colormap instead of a line.
Plots the magnitude spectrum.
Plots the spectral density between two signals.
For plotting, the power is plotted as \(10\log_{10}(P_{xx})\) for decibels, though Pxx itself is returned.
Bendat & Piersol -- Random Data: Analysis and Measurement Procedures, John Wiley & Sons (1986)


Plot a 2D field of arrows.
Call signature:
X, Y define the arrow locations, U, V define the arrow directions, and C optionally sets the color.
Each arrow is internally represented by a filled polygon with a default edge linewidth of 0. As a result, an arrow is rather a filled area, not a line with a head, and PolyCollection properties like linewidth, linestyle, facecolor, etc. act accordingly.
Arrow size
The default settings auto-scales the length of the arrows to a reasonable size. To change this behavior see the scale and scale_units parameters.
Arrow shape
The defaults give a slightly swept-back arrow; to make the head a triangle, make headaxislength the same as headlength. To make the arrow more pointed, reduce headwidth or increase headlength and headaxislength. To make the head smaller relative to the shaft, scale down all the head parameters. You will probably do best to leave minshaft alone.
Arrow outline
linewidths and edgecolors can be used to customize the arrow outlines.
The x and y coordinates of the arrow locations.
If not given, they will be generated as a uniform integer meshgrid based on the dimensions of U and V.
If X and Y are 1D but U, V are 2D, X, Y are expanded to 2D using X, Y = np.meshgrid(X, Y). In this case len(X) and len(Y) must match the column and row dimensions of U and V.
The x and y direction components of the arrow vectors.
They must have the same number of elements, matching the number of arrow locations. U and V may be masked. Only locations unmasked in U, V, and C will be drawn.
Numeric data that defines the arrow colors by colormapping via norm and cmap.
This does not support explicit colors. If you want to set colors directly, use color instead. The size of C must match the number of arrow locations.
The arrow dimensions (except for length) are measured in multiples of this unit.
The following values are supported:
The arrows scale differently depending on the units. For 'x' or 'y', the arrows get larger as one zooms in; for other units, the arrow size is independent of the zoom state. For 'width or 'height', the arrow size increases with the width and height of the axes, respectively, when the window is resized; for 'dots' or 'inches', resizing does not change the arrows.
Method for determining the angle of the arrows.
'uv': The arrow axis aspect ratio is 1 so that if U == V the orientation of the arrow on the plot is 45 degrees counter-clockwise from the horizontal axis (positive to the right).
Use this if the arrows symbolize a quantity that is not based on X, Y data coordinates.
Alternatively, arbitrary angles may be specified explicitly as an array of values in degrees, counter-clockwise from the horizontal axis.
In this case U, V is only used to determine the length of the arrows.
Note: inverting a data axis will correspondingly invert the arrows only with angles='xy'.
Number of data units per arrow length unit, e.g., m/s per plot width; a smaller scale parameter makes the arrow longer. Default is None.
If None, a simple autoscaling algorithm is used, based on the average vector length and the number of vectors. The arrow length unit is given by the scale_units parameter.
If the scale kwarg is None, the arrow length unit. Default is None.
e.g. scale_units is 'inches', scale is 2.0, and (u, v) = (1, 0), then the vector will be 0.5 inches long.
If scale_units is 'width' or 'height', then the vector will be half the width/height of the axes.
If scale_units is 'x' then the vector will be 0.5 x-axis units. To plot vectors in the x-y plane, with u and v having the same units as x and y, use angles='xy', scale_units='xy', scale=1.
Shaft width in arrow units; default depends on choice of units, above, and number of vectors; a typical starting value is about 0.005 times the width of the plot.
Head width as multiple of shaft width.
Head length as multiple of shaft width.
Head length at shaft intersection.
Length below which arrow scales, in units of head length. Do not set this to less than 1, or small arrows will look terrible!
Minimum length as a multiple of shaft width; if an arrow length is less than this, plot a dot (hexagon) of this diameter instead.
The part of the arrow that is anchored to the X, Y grid. The arrow rotates about this point.
'mid' is a synonym for 'middle'.
Explicit color(s) for the arrows. If C has been set, color has no effect.
This is a synonym for the PolyCollection facecolor parameter.
If given, all parameters also accept a string s, which is interpreted as data[s] (unless this raises an exception).
All other keyword arguments are passed on to PolyCollection:
Property
Description
agg_filter
a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha
array-like or scalar 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
Bbox
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 colors or 'face'
facecolor or facecolors or fc
color or list of colors
figure
Figure
gid
str
hatch
{'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
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
norm
Normalize or None
offset_transform
Transform
offsets
(N, 2) or (2,) array-like
path_effects
AbstractPathEffect
paths
list of array-like
picker
None or bool or float or callable
pickradius
float
rasterized
bool
sizes
ndarray or None
sketch_params
(scale: float, length: float, randomness: float)
snap
bool or None
transform
Transform
url
str
urls
list of str or None
verts
list of array-like
verts_and_codes
unknown
visible
bool
zorder
float
See also
Add a key to a quiver plot.


Add a key to a quiver plot.
The positioning of the key depends on X, Y, coordinates, and labelpos. If labelpos is 'N' or 'S', X, Y give the position of the middle of the key arrow. If labelpos is 'E', X, Y positions the head, and if labelpos is 'W', X, Y positions the tail; in either of these two cases, X, Y is somewhere in the middle of the arrow+label key object.
A Quiver object as returned by a call to quiver().
The location of the key.
The length of the key.
The key label (e.g., length and units of the key).
The angle of the key arrow, in degrees anti-clockwise from the x-axis.
Coordinate system and units for X, Y: 'axes' and 'figure' are normalized coordinate systems with (0, 0) in the lower left and (1, 1) in the upper right; 'data' are the axes data coordinates (used for the locations of the vectors in the quiver plot itself); 'inches' is position in the figure in inches, with (0, 0) at the lower left corner.
Overrides face and edge colors from Q.
Position the label above, below, to the right, to the left of the arrow, respectively.
Distance in inches between the arrow and the label.
Label color.
A dictionary with keyword arguments accepted by the FontProperties initializer: family, style, variant, size, weight.
Any additional keyword arguments are used to override vector properties taken from Q.


Set the current rcParams. group is the grouping for the rc, e.g., for lines.linewidth the group is lines, for axes.facecolor, the group is axes, and so on. Group may also be a list or tuple of group names, e.g., (xtick, ytick). kwargs is a dictionary attribute name/value pairs, e.g.,:
sets the current rcParams and is equivalent to:
The following aliases are available to save typing for interactive users:
Alias
Property
'lw'
'linewidth'
'ls'
'linestyle'
'c'
'color'
'fc'
'facecolor'
'ec'
'edgecolor'
'mew'
'markeredgewidth'
'aa'
'antialiased'
Thus you could abbreviate the above call as:
Note you can use python's kwargs dictionary facility to store dictionaries of default parameters. e.g., you can customize the font rc as follows:
This enables you to easily switch between several configurations. Use matplotlib.style.use('default') or rcdefaults() to restore the default rcParams after changes.
Similar functionality is available by using the normal dict interface, i.e. rcParams.update({"lines.linewidth": 2, ...}) (but rcParams.update does not support abbreviations or grouping).
Styling with cycler


Return a context manager for temporarily changing rcParams.
The rcParams to temporarily set.
A file with Matplotlib rc settings. If both fname and rc are given, settings from rc take precedence.
See also
Passing explicit values via a dict:
Loading settings from a file:
Style sheets reference
Matplotlib logo


Restore the rcParams from Matplotlib's internal default style.
Style-blacklisted rcParams (defined in matplotlib.style.core.STYLE_BLACKLIST) are not updated.
See also
Restore the rcParams from the rc file originally loaded by Matplotlib.
Use a specific style file. Call style.use('default') to restore the default style.
Horizontal bar chart
Customize Rc


Get or set the radial gridlines on the current polar plot.
Call signatures:
When called with no arguments, rgrids simply returns the tuple (lines, labels). When called with arguments, the labels will appear at the specified radial distances and angle.
The radii for the radial gridlines
The labels to use at each radial gridline. The matplotlib.ticker.ScalarFormatter will be used if None.
The angular position of the radius labels in degrees.
Format string used in matplotlib.ticker.FormatStrFormatter. For example '%f'.
The radial gridlines.
The tick labels.
kwargs are optional Text properties for the labels.
See also


Save the current figure.
Call signature:
The available output formats depend on the backend being used.
A path, or a Python file-like object, or possibly some backend-dependent object such as matplotlib.backends.backend_pdf.PdfPages.
If format is set, it determines the output format, and the file is saved as fname. Note that fname is used verbatim, and there is no attempt to make the extension, if any, of fname match format, and no extension is appended.
If format is not set, then the format is inferred from the extension of fname, if there is one. If format is not set and fname has no extension, then the file is saved with rcParams["savefig.format"] (default: 'png') and the appropriate extension is appended to fname.
The resolution in dots per inch. If 'figure', use the figure's dpi value.
The file format, e.g. 'png', 'pdf', 'svg', ... The behavior when this is unset is documented under fname.
Key/value pairs to store in the image metadata. The supported keys and defaults depend on the image format and backend:
Bounding box in inches: only the given portion of the figure is saved. If 'tight', try to figure out the tight bbox of the figure.
Amount of padding around the figure when bbox_inches is 'tight'.
The facecolor of the figure. If 'auto', use the current figure facecolor.
The edgecolor of the figure. If 'auto', use the current figure edgecolor.
Use a non-default backend to render the file, e.g. to render a png file with the "cairo" backend rather than the default "agg", or a pdf file with the "pgf" backend rather than the default "pdf". Note that the default backend is normally sufficient. See The builtin backends for a list of valid backends for each file format. Custom backends can be referenced as "module://...".
Currently only supported by the postscript backend.
One of 'letter', 'legal', 'executive', 'ledger', 'a0' through 'a10', 'b0' through 'b10'. Only supported for postscript output.
If True, the Axes patches will all be transparent; the Figure patch will also be transparent unless facecolor and/or edgecolor are specified via kwargs.
If False has no effect and the color of the Axes and Figure patches are unchanged (unless the Figure patch is specified via the facecolor and/or edgecolor keyword arguments in which case those colors are used).
The transparency of these patches will be restored to their original values upon exit of this function.
This is useful, for example, for displaying a plot on top of a colored background on a web page.
A list of extra artists that will be considered when the tight bbox is calculated.
Additional keyword arguments that are passed to PIL.Image.Image.save when saving the figure.
Print Stdout
Rasterization for vector graphics
SVG Filter Line
SVG Filter Pie
SVG Histogram
SVG Tooltip


Set the current Axes to ax and the current Figure to the parent of ax.


A scatter plot of y vs. x with varying marker size and/or color.
The data positions.
The marker size in points**2. Default is rcParams['lines.markersize'] ** 2.
The marker colors. Possible values:
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 rcParams["axes.prop_cycle"] (default: cycler('color', ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf'])).
The marker style. marker can be either an instance of the class or the text shorthand for a particular marker. See matplotlib.markers for more information about marker styles.
A Colormap instance or registered colormap name. cmap is only used if c is an array of floats.
If c is an array of floats, norm is used to scale the color data, c, in the range 0 to 1, in order to map into the colormap cmap. If None, use the default colors.Normalize.
vmin and vmax are used in conjunction with the default norm to map the color array c to the colormap cmap. If None, the respective min and max of the color array is used. It is an error to use vmin/vmax when norm is given.
The alpha blending value, between 0 (transparent) and 1 (opaque).
The linewidth of the marker edges. Note: The default edgecolors is 'face'. You may want to change this as well.
The edge color of the marker. Possible values:
For non-filled markers, edgecolors is ignored. Instead, the color is determined like with 'face', i.e. from c, colors, or facecolors.
Whether to plot points with nonfinite c (i.e. inf, -inf or nan). If True the points are drawn with the bad colormap color (see Colormap.set_bad).
If given, the following parameters also accept a string s, which is interpreted as data[s] (unless this raises an exception):
x, y, s, linewidths, edgecolors, c, facecolor, facecolors, color
See also
To plot scatter plots when markers are identical in size and color.
Scatter Masked
Scatter Symbol
Scatter plot
Hyperlinks
Pyplot tutorial


Set the current image.
This image will be the target of colormap functions like viridis, and other functions such as clim. The current image is an attribute of the current Axes.
Line Collection


Make a plot with log scaling on the x axis.
Call signatures:
This is just a thin wrapper around plot which additionally changes the x-axis to log scaling. All of the concepts and parameters of plot can be used here as well.
The additional parameters base, subs, and nonpositive control the x-axis properties. They are just forwarded to Axes.set_xscale.
Base of the x logarithm.
The location of the minor xticks. If None, reasonable locations are automatically chosen depending on the number of decades in the plot. See Axes.set_xscale for details.
Non-positive values in x can be masked as invalid, or clipped to a very small positive number.
All parameters supported by plot.
Objects representing the plotted data.


Make a plot with log scaling on the y axis.
Call signatures:
This is just a thin wrapper around plot which additionally changes the y-axis to log scaling. All of the concepts and parameters of plot can be used here as well.
The additional parameters base, subs, and nonpositive control the y-axis properties. They are just forwarded to Axes.set_yscale.
Base of the y logarithm.
The location of the minor yticks. If None, reasonable locations are automatically chosen depending on the number of decades in the plot. See Axes.set_yscale for details.
Non-positive values in y can be masked as invalid, or clipped to a very small positive number.
All parameters supported by plot.
Objects representing the plotted data.


Set the default colormap, and applies it to the current image if any.
A colormap instance or the name of a registered colormap.
See also


Set Matplotlib's root logger and root logger handler level, creating the handler if it does not exist yet.
Typically, one should call set_loglevel("info") or set_loglevel("debug") to get additional debugging information.
The log level of the handler.
The first time this function is called, an additional handler is attached to Matplotlib's root handler; this handler is reused every time and this function simply manipulates the logger and handler's level.


Set one or more properties on an Artist, or list allowed values.
The artist(s) whose properties are being set or queried. When setting properties, all artists are affected; when querying the allowed values, only the first instance in the sequence is queried.
For example, two lines can be made thicker and red with a single call:
Where setp writes its output when asked to list allowed values.
The default, None, means sys.stdout.
The properties to set. The following combinations are supported:
Set the linestyle of a line to be dashed:
Set multiple properties at once:
List allowed values for a line's linestyle:
List all properties that can be set, and their allowed values:
setp also supports MATLAB style string/value pairs. For example, the following are equivalent:
See also
Creating a timeline with lines, dates, and text
Contouring the solution space of optimizations
Creating annotated heatmaps
Boxplots
Pie Demo2
Labeling a pie and a donut
Patheffect Demo
Set and get properties
TickedStroke patheffect
Topographic hillshading
Evans test
The Lifecycle of a Plot


Display all open figures.
Whether to wait for all figures to be closed before returning.
If True block and run the GUI main loop until all figure windows are closed.
If False ensure that all figure windows are displayed and return immediately. In this case, you are responsible for ensuring that the event loop is running to have responsive figures.
Defaults to True in non-interactive mode and to False in interactive mode (see pyplot.isinteractive).
See also
Enable interactive mode, which shows / updates the figure after every plotting command, so that calling show() is not necessary.
Disable interactive mode.
Save the figure to an image file instead of showing it on screen.
Saving figures to file and showing a window at the same time
If you want an image file as well as a user interface window, use pyplot.savefig before pyplot.show. At the end of (a blocking) show() the figure is closed and thus unregistered from pyplot. Calling pyplot.savefig afterwards would save a new and thus empty figure. This limitation of command order does not apply if the show is non-blocking or if you keep a reference to the figure and use Figure.savefig.
Auto-show in jupyter notebooks
The jupyter backends (activated via %matplotlib inline, %matplotlib notebook, or %matplotlib widget), call show() at the end of every cell by default. Thus, you usually don't have to call it explicitly there.
Bar Label Demo
Stacked bar chart
Grouped bar chart with labels
Horizontal bar chart
Broken Barh
CapStyle
Plotting categorical variables
Plotting the coherence of two signals
CSD Demo
Curve with error band
Errorbar limit selection
Errorbar subsampling
EventCollection Demo
Eventplot Demo
Filled polygon
Fill Between and Alpha
Fill Betweenx Demo
Hatch-filled histograms
Bar chart with gradients
Hat graph
Discrete distribution as horizontal bar chart
JoinStyle
Customizing dashed line styles
Lines with a ticked patheffect
Linestyles
Marker reference
Markevery Demo
prop_cycle property markevery in rcParams
Plotting masked and NaN values
Multicolored lines
Psd Demo
Scatter Custom Symbol
Scatter Demo2
Scatter plot with histograms
Scatter Masked
Scatter plot with pie chart markers
Marker examples
Scatter Symbol
Scatter plots with a legend
Simple Plot
Using span_where
Spectrum Representations
Stackplots and streamgraphs
Stairs Demo
Stem Plot
Step Demo
Creating a timeline with lines, dates, and text
hlines and vlines
Cross- and Auto-Correlation Demo
Affine transform of an image
Wind Barbs
Barcode
Contour Corner Mask
Contour Demo
Contour Image
Contour Label Demo
Contourf Demo
Contourf Hatching
Contourf and log color scale
Contouring the solution space of optimizations
BboxImage Demo
Figimage Demo
Creating annotated heatmaps
Image antialiasing
Clipping images with patches
Image Demo
Image Masked
Image Nonuniform
Blend transparency with color in 2D images
Modifying the coordinate formatter
Interpolations for imshow
Contour plot of irregularly spaced data
Layer Images
Matshow
Multi Image
Pcolor Demo
pcolormesh grids and shading
pcolormesh
Streamplot
QuadMesh Demo
Advanced quiver and quiverkey functions
Quiver Simple Demo
Shading example
Spectrogram Demo
Spy Demos
Tricontour Demo
Tricontour Smooth Delaunay
Tricontour Smooth User
Trigradient Demo
Triinterp Demo
Tripcolor Demo
Triplot Demo
Watermark image
Aligning Labels
Axes box aspect
Axes Demo
Controlling view limits using margins and sticky_edges
Axes Props
Axes Zoom Effect
axhspan Demo
Equal axis aspect ratio
Axis Label Position
Broken Axis
Placing Colorbars
Resizing axes with constrained layout
Resizing axes with tight layout
Different scales on the same axes
Figure size in different units
Figure labels: suptitle, supxlabel, supylabel
Creating adjacent subplots
Geographic Projections
Combining two subplots using subplots and GridSpec
Using Gridspec to make multi-column/row subplot layouts
Nested Gridspecs
Invert Axes
Managing multiple figures in pyplot
Secondary Axis
Sharing axis limits and views
Shared Axis
Figure subfigures
Multiple subplots
Subplots spacings and margins
Creating multiple subplots using plt.subplots
Plots with different scales
Zoom region inset axes
Percentiles as horizontal bar chart
Artist customization in box plots
Box plots with custom fill colors
Boxplots
Box plot vs. violin plot comparison
Boxplot drawer function
Plot a confidence ellipse of a two-dimensional dataset
Violin plot customization
Errorbar function
Different ways of specifying error bars
Including upper and lower limits in error bars
Creating boxes from error bars using PatchCollection
Hexagonal binned plot
Histograms
Using histograms to plot a cumulative distribution
Some features of the histogram (hist) function
Demo of the histogram function's different histtype settings
The histogram (hist) function with multiple data sets
Producing multiple histograms side by side
Time Series Histogram
Violin plot basics
Basic pie chart
Pie Demo2
Bar of pie
Nested pie charts
Labeling a pie and a donut
Bar chart on polar axis
Polar plot
Polar Legend
Scatter plot on polar axis
Using accented text in matplotlib
Scale invariant angle label
Annotating Plots
Arrow Demo
Auto-wrapping text
Composing Custom Legends
Date tick labels
Custom tick formatter for time series
AnnotationBbox demo
Using a text as a Path
Text Rotation Mode
The difference between \dfrac and \frac
Labeling ticks using engineering notation
Annotation arrow style reference
Styling text boxes
Figure legend demo
Configuring the font family
Using a ttf font file in Matplotlib
Font table
Fonts demo (object-oriented style)
Fonts demo (keyword arguments)
Labelling subplots
Legend using pre-defined labels
Legend Demo
Artist within an artist
Convert texts to images
Mathtext
Mathtext Examples
Math fontfamily
Multiline
Placing text boxes
Rainbow text
STIX Fonts
Rendering math equations using TeX
Precise text layout
Controlling style of text and labels using a dictionary
Default text rotation demonstration
Text Rotation Relative To Line
Title positioning
Unicode minus
Usetex Baseline Test
Usetex Fonteffects
Text watermark
Align y-labels
Annotate Transform
Annotating a plot
Annotation Polar
Programmatically controlling subplot adjustment
Infinite lines
Boxplot Demo
Dollar Ticks
Fig Axes Customize Simple
Simple axes labels
Adding lines to figures
plot() format string
Pyplot Mathtext
Pyplot Simple
Pyplot Text
Pyplot Three
Pyplot Two Subplots
Text Commands
Text Layout
Color Demo
Color by y-value
Colors in the default property cycle
Colorbar
Colormap reference
Creating a colormap from a list of colors
List of named colors
Arrow guide
Reference for Matplotlib artists
Line, Poly and RegularPoly Collection with autoscaling
Compound path
Dolphins
Mmh Donuts!!!
Ellipse Collection
Ellipse Demo
Drawing fancy boxes
Hatch demo
Line Collection
Circles, Wedges and Polygons
PathPatch object
Bezier Curve
Scatter plot
Bayesian Methods for Hackers style sheet
Dark background style sheet
FiveThirtyEight style sheet
ggplot style sheet
Grayscale style sheet
Solarized Light stylesheet
Style sheets reference
Anchored Direction Arrow
Axes Divider
Demo Axes Grid
Axes Grid2
HBoxDivider demo
Showing RGB channels using RGBAxes
Adding a colorbar to inset axes
Colorbar with AxesDivider
Controlling the position and size of colorbars with Inset Axes
Per-row or per-column colorbars
Axes with a fixed physical size
Setting a fixed aspect on ImageGrid cells
Inset Locator Demo
Inset Locator Demo2
Make Room For Ylabel Using Axesgrid
Parasite Simple
Parasite Simple2
Scatter Histogram (Locatable Axes)
Simple Anchored Artists
Simple Axes Divider 1
Simple Axes Divider 3
Simple ImageGrid
Simple ImageGrid 2
Simple Axisline4
Simple Colorbar
Axis Direction
axis_direction demo
Axis line styles
Curvilinear grid demo
Demo CurveLinear Grid2
mpl_toolkits.axisartist.floating_axes features
floating_axis demo
Parasite Axes demo
Parasite axis demo
Ticklabel alignment
Ticklabel direction
Simple Axis Direction01
Simple Axis Direction03
Simple Axis Pad
Custom spines with axisartist
Simple Axisline
Simple Axisline3
Anatomy of a figure
Bachelor's degrees by gender
Firefox
Integral as the area under a curve
Shaded & power normalized rendering
XKCD
Decay
Animated histogram
The Bayes update
The double pendulum problem
Animated image using a precomputed list of images
Pausing and Resuming an Animation
Rain simulation
Animated 3D random walk
Animated line plot
Oscilloscope
MATPLOTLIB UNCHAINED
Close Event
Mouse move and click events
Data Browser
Figure/Axes enter and leave events
Interactive functions
Image Slices Viewer
Keypress event
Lasso Demo
Legend Picking
Looking Glass
Path Editor
Pick Event Demo
Pick Event Demo2
Poly Editor
Pong
Resampling Data
Timers
Trifinder Event Demo
Viewlims
Zoom Window
Frontpage contour example
Anchored Artists
Changing colors of lines intersecting a box
Manual Contour
Coords Report
Cross hair cursor
Custom projection
Customize Rc
AGG filter
Ribbon Box
Fill Spiral
Findobj Demo
Building histograms using Rectangles and PolyCollections
Plotting with keywords
Matplotlib logo
Multiprocess
Packed-bubble chart
Patheffect Demo
Pythonic Matplotlib
Set and get properties
Table Demo
TickedStroke patheffect
transforms.offset_copy
Zorder Demo
Plot 2D data on 3D plot
Demo of 3D bar charts
Create 2D bar graphs in different planes
3D box surface plot
Demonstrates plotting contour (level) curves in 3D
Demonstrates plotting contour (level) curves in 3D using the extend3d option
Projecting contour profiles onto a graph
Filled contours
Projecting filled contour onto a graph
Custom hillshading in a 3D surface plot
3D errorbars
Create 3D histogram of 2D data
Parametric Curve
Lorenz Attractor
2D and 3D Axes in same Figure
Automatic Text Offsetting
Draw flat objects in 3D plot
Generate polygons to fill under 3D line graph
3D quiver plot
3D scatterplot
3D stem
3D plots as subplots
3D surface (colormap)
3D surface (solid color)
3D surface (checkerboard)
3D surface with polar coordinates
Text annotations in 3D
Triangular 3D contour plot
Triangular 3D filled contour plot
Triangular 3D surfaces
More triangular 3D surfaces
3D voxel / volumetric plot
3D voxel plot of the numpy logo
3D voxel / volumetric plot with rgb colors
3D voxel / volumetric plot with cylindrical coordinates
3D wireframe plot
3D wireframe plots in one direction
Loglog Aspect
Custom scale
Log Bar
Log Demo
Log Axis
Logit Demo
Exploring normalizations
Scales
Symlog Demo
Hillshading
Anscombe's quartet
Hinton diagrams
Left ventricle bullseye
MRI
MRI With EEG
Radar chart (aka spider or star chart)
The Sankey class
Long chain of connections using Sankey
Rankine power cycle
SkewT-logP diagram: using transforms and custom projections
Topographic hillshading
Centered spines with arrows
Multiple Yaxis With Spines
Spine Placement
Spines
Custom spine bounds
Dropped spines
Automatically setting tick positions
Centering labels between ticks
Colorbar Tick Labelling
Custom Ticker1
Formatting date ticks using ConciseDateFormatter
Date Demo Convert
Placing date ticks using recurrence rules
Date Index Formatter
Date Precision and Epochs
Major and minor ticks
The default tick formatter
Tick formatters
Tick locators
Set default y-axis tick labels on the right
Setting tick labels from a list of values
Set default x-axis tick labels on the top
Rotating custom tick labels
Annotation with units
Artist tests
Bar demo with units
Group barchart with units
Ellipse With Units
Evans test
Radian ticks
Inches and Centimeters
Unit handling
pyplot with GTK3
pyplot with GTK4
Tool Manager
Anchored Box04
Annotate Explain
Annotate Simple01
Annotate Simple02
Annotate Simple03
Annotate Simple04
Annotate Simple Coord01
Annotate Simple Coord02
Annotate Simple Coord03
Annotate Text Arrow
Interactive Adjustment of Colormap Range
Colormap Normalizations
Colormap Normalizations Symlognorm
Connect Simple01
Connection styles for annotations
Custom box styles
subplot2grid demo
GridSpec demo
Nested GridSpecs
Simple Annotate01
Simple Legend01
Simple Legend02
Annotated Cursor
Buttons
Check Buttons
Cursor
Lasso Selector
Menu
Mouse Cursor
Multicursor
Polygon Selector
Radio Buttons
Thresholding an Image with RangeSlider
Rectangle and ellipse selectors
Slider
Snapping Sliders to Discrete Values
Span Selector
Textbox
Pyplot tutorial
The Lifecycle of a Plot
Customizing Matplotlib with style sheets and rcParams
Artist tutorial
Legend guide
Styling with cycler
Constrained Layout Guide
Tight Layout guide
Arranging multiple Axes in a Figure
origin and extent in imshow
Faster rendering by using blitting
Path Tutorial
Path effects guide
Transformations Tutorial
Specifying Colors
Customized Colorbars Tutorial
Creating Colormaps in Matplotlib
Colormap Normalization
Choosing Colormaps in Matplotlib
Text in Matplotlib Plots
Text properties and layout
plot(x, y)
scatter(x, y)
bar(x, height) / barh(y, width)
stem(x, y)
step(x, y)
fill_between(x, y1, y2)
imshow(Z)
pcolormesh(X, Y, Z)
contour(X, Y, Z)
contourf(X, Y, Z)
barbs(X, Y, U, V)
quiver(X, Y, U, V)
streamplot(X, Y, U, V)
hist(x)
boxplot(X)
errorbar(x, y, yerr, xerr)
violinplot(D)
eventplot(D)
hist2d(x, y)
hexbin(x, y, C)
pie(x)
tricontour(x, y, z)
tricontourf(x, y, z)
tripcolor(x, y, z)
triplot(x, y)


Plot a spectrogram.
Compute and plot a spectrogram of data in x. Data are split into NFFT length segments and the spectrum of each section is computed. The windowing function window is applied to each segment, and the amount of overlap of each segment is specified with noverlap. The spectrogram is plotted as a colormap (using imshow).
Array or sequence containing the data.
The sampling frequency (samples per time unit). It is used to calculate the Fourier frequencies, freqs, in cycles per time unit.
A function or a vector of length NFFT. To create window vectors see window_hanning, window_none, numpy.blackman, numpy.hamming, numpy.bartlett, scipy.signal, scipy.signal.get_window, etc. If a function is passed as the argument, it must take a data segment as an argument and return the windowed version of the segment.
Which sides of the spectrum to return. 'default' is one-sided for real data and two-sided for complex data. 'onesided' forces the return of a one-sided spectrum, while 'twosided' forces two-sided.
The number of points to which the data segment is padded when performing the FFT. This can be different from NFFT, which specifies the number of data points used. While not increasing the actual resolution of the spectrum (the minimum distance between resolvable peaks), this can give more points in the plot, allowing for more detail. This corresponds to the n parameter in the call to fft(). The default is None, which sets pad_to equal to NFFT
The number of data points used in each block for the FFT. A power 2 is most efficient. This should NOT be used to get zero padding, or the scaling of the result will be incorrect; use pad_to for this instead.
The function applied to each segment before fft-ing, designed to remove the mean or linear trend. Unlike in MATLAB, where the detrend parameter is a vector, in Matplotlib it is a function. The mlab module defines detrend_none, detrend_mean, and detrend_linear, but you can use a custom function as well. You can also use a string to choose one of the functions: 'none' calls detrend_none. 'mean' calls detrend_mean. 'linear' calls detrend_linear.
Whether the resulting density values should be scaled by the scaling frequency, which gives density in units of Hz^-1. This allows for integration over the returned frequency values. The default is True for MATLAB compatibility.
What sort of spectrum to use. Default is 'psd', which takes the power spectral density. 'magnitude' returns the magnitude spectrum. 'angle' returns the phase spectrum without unwrapping. 'phase' returns the phase spectrum with unwrapping.
The number of points of overlap between blocks.
The scaling of the values in the spec. 'linear' is no scaling. 'dB' returns the values in dB scale. When mode is 'psd', this is dB power (10 * log10). Otherwise this is dB amplitude (20 * log10). 'default' is 'dB' if mode is 'psd' or 'magnitude' and 'linear' otherwise. This must be 'linear' if mode is 'angle' or 'phase'.
The center frequency of x, which offsets the x extents of the plot to reflect the frequency range used when a signal is acquired and then filtered and downsampled to baseband.
The image extent along the x-axis. The default sets xmin to the left border of the first bin (spectrum column) and xmax to the right border of the last bin. Note that for noverlap>0 the width of the bins is smaller than those of the segments.
If given, the following parameters also accept a string s, which is interpreted as data[s] (unless this raises an exception):
x
Additional keyword arguments are passed on to imshow which makes the specgram image. The origin keyword argument is not supported.
Columns are the periodograms of successive segments.
The frequencies corresponding to the rows in spectrum.
The times corresponding to midpoints of segments (i.e., the columns in spectrum).
The image created by imshow containing the spectrogram.
See also
Differs in the default overlap; in returning the mean of the segment periodograms; in not returning times; and in generating a line plot instead of colormap.
A single spectrum, similar to having a single segment when mode is 'magnitude'. Plots a line instead of a colormap.
A single spectrum, similar to having a single segment when mode is 'angle'. Plots a line instead of a colormap.
A single spectrum, similar to having a single segment when mode is 'phase'. Plots a line instead of a colormap.
The parameters detrend and scale_by_freq do only apply when mode is set to 'psd'.


Set the colormap to 'spring'.
This changes the default colormap as well as the colormap of the current image if there is one. See help(colormaps) for more information.


Plot the sparsity pattern of a 2D array.
This visualizes the non-zero values of the array.
Two plotting styles are available: image and marker. Both are available for full arrays, but only the marker style works for scipy.sparse.spmatrix instances.
Image style
If marker and markersize are None, imshow is used. Any extra remaining keyword arguments are passed to this method.
Marker style
If Z is a scipy.sparse.spmatrix or marker or markersize are None, a Line2D object will be returned with the value of marker determining the marker type, and any remaining keyword arguments passed to plot.
The array to be plotted.
If precision is 0, any non-zero value will be plotted. Otherwise, values of \(|Z| > precision\) will be plotted.
For scipy.sparse.spmatrix instances, you can also pass 'present'. In this case any value present in the array will be plotted, even if it is identically zero.
The aspect ratio of the Axes. This parameter is particularly relevant for images since it determines whether data pixels are square.
This parameter is a shortcut for explicitly calling Axes.set_aspect. See there for further details.
Place the [0, 0] index of the array in the upper left or lower left corner of the Axes. The convention 'upper' is typically used for matrices and images.
The return type depends on the plotting style (see above).
The supported additional parameters depend on the plotting style.
For the image style, you can pass the following additional parameters of imshow:
For the marker style, you can pass any Line2D property except for linestyle:
Property
Description
agg_filter
a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha
scalar or None
animated
bool
antialiased or aa
bool
clip_box
Bbox
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
Figure
fillstyle
{'full', 'left', 'right', 'bottom', 'top', 'none'}
gid
str
in_layout
bool
label
object
linestyle or ls
{'-', '--', '-.', ':', '', (offset, on-off-seq), ...}
linewidth or lw
float
marker
marker style string, Path or 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]
path_effects
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


Draw a stacked area plot.
The data is assumed to be unstacked. Each of the following calls is legal:
Method used to calculate the baseline:
A sequence of labels to assign to each data series. If unspecified, then no labels will be applied to artists.
A sequence of colors to be cycled through and used to color the stacked areas. The sequence need not be exactly the same length as the number of provided y, in which case the colors will repeat from the beginning.
If not specified, the colors from the Axes property cycle will be used.
If given, all parameters also accept a string s, which is interpreted as data[s] (unless this raises an exception).
All other keyword arguments are passed to Axes.fill_between.
A list of PolyCollection instances, one for each element in the stacked area plot.


A stepwise constant function as a line with bounding edges or a filled plot.
The step heights.
The edge positions, with len(edges) == len(vals) + 1, between which the curve takes on vals values.
The direction of the steps. Vertical means that values are along the y-axis, and edges are along the x-axis.
The bottom value of the bounding edges or when fill=True, position of lower edge. If fill is True or an array is passed to baseline, a closed path is drawn.
Whether the area under the step curve should be filled.
If given, all parameters also accept a string s, which is interpreted as data[s] (unless this raises an exception).
StepPatch properties
Stairs Demo


Create a stem plot.
A stem plot draws lines perpendicular to a baseline at each location locs from the baseline to heads, and places a marker there. For vertical stem plots (the default), the locs are x positions, and the heads are y values. For horizontal stem plots, the locs are y positions, and the heads are x values.
Call signature:
The locs-positions are optional. The formats may be provided either as positional or as keyword-arguments.
For vertical stem plots, the x-positions of the stems. For horizontal stem plots, the y-positions of the stems.
For vertical stem plots, the y-values of the stem heads. For horizontal stem plots, the x-values of the stem heads.
A string defining the color and/or linestyle of the vertical lines:
Character
Line Style
'-'
solid line
'--'
dashed line
'-.'
dash-dot line
':'
dotted line
Default: 'C0-', i.e. solid line with the first color of the color cycle.
Note: Markers specified through this parameter (e.g. 'x') will be silently ignored (unless using use_line_collection=False). Instead, markers should be specified using markerfmt.
A string defining the color and/or shape of the markers at the stem heads. Default: 'C0o', i.e. filled circles with the first color of the color cycle.
A format string defining the properties of the baseline.
If 'vertical', will produce a plot with stems oriented vertically, otherwise the stems will be oriented horizontally.
The y/x-position of the baseline (depending on orientation).
The label to use for the stems in legends.
If True, store and plot the stem lines as a LineCollection instead of individual lines, which significantly increases performance. If False, defaults to the old behavior of using a list of Line2D objects. This parameter may be deprecated in the future.
If given, all parameters also accept a string s, which is interpreted as data[s] (unless this raises an exception).
The container may be treated like a tuple (markerline, stemlines, baseline)
See also
The MATLAB function stem which inspired this method.
Stem Plot


Make a step plot.
Call signatures:
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 stairs instead.
1D sequence of x positions. It is assumed, but not checked, that it is uniformly increasing.
1D sequence of y levels.
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.
Define where the steps should be placed:
An object with labelled data. If given, provide the label names to plot in x and y.
Additional parameters are the same as those for plot.
Objects representing the plotted data.
Stairs Demo
Step Demo