Draw a box and whisker plot.
The box extends from the first quartile (Q1) to the third quartile (Q3) of the data, with a line at the median. The whiskers extend from the box by 1.5x the inter-quartile range (IQR). Flier points are those past the end of the whiskers. See https://en.wikipedia.org/wiki/Box_plot for reference.
The input data. If a 2D array, a boxplot is drawn for each column in x. If a sequence of 1D arrays, a boxplot is drawn for each array in x.
Whether to draw a notched boxplot (True), or a rectangular boxplot (False). The notches represent the confidence interval (CI) around the median. The documentation for bootstrap describes how the locations of the notches are computed by default, but their locations may also be overridden by setting the conf_intervals parameter.
Note
In cases where the values of the CI are less than the lower quartile or greater than the upper quartile, the notches will extend beyond the box, giving it a distinctive "flipped" appearance. This is expected behavior and consistent with other statistical visualization packages.
The default symbol for flier points. An empty string ('') hides the fliers. If None, then the fliers default to 'b+'. More control is provided by the flierprops parameter.
If True, draws vertical boxes. If False, draw horizontal boxes.
The position of the whiskers.
If a float, the lower whisker is at the lowest datum above Q1 - whis*(Q3-Q1), and the upper whisker at the highest datum below Q3 + whis*(Q3-Q1), where Q1 and Q3 are the first and third quartiles. The default value of whis = 1.5 corresponds to Tukey's original definition of boxplots.
If a pair of floats, they indicate the percentiles at which to draw the whiskers (e.g., (5, 95)). In particular, setting this to (0, 100) results in whiskers covering the whole range of the data.
In the edge case where Q1 == Q3, whis is automatically set to (0, 100) (cover the whole range of the data) if autorange is True.
Beyond the whiskers, data are considered outliers and are plotted as individual points.
Specifies whether to bootstrap the confidence intervals around the median for notched boxplots. If bootstrap is None, no bootstrapping is performed, and notches are calculated using a Gaussian-based asymptotic approximation (see McGill, R., Tukey, J.W., and Larsen, W.A., 1978, and Kendall and Stuart, 1967). Otherwise, bootstrap specifies the number of times to bootstrap the median to determine its 95% confidence intervals. Values between 1000 and 10000 are recommended.
A 1D array-like of length len(x). Each entry that is not None forces the value of the median for the corresponding dataset. For entries that are None, the medians are computed by Matplotlib as normal.
A 2D array-like of shape (len(x), 2). Each entry that is not None forces the location of the corresponding notch (which is only drawn if notch is True). For entries that are None, the notches are computed by the method specified by the other parameters (e.g., bootstrap).
The positions of the boxes. The ticks and limits are automatically set to match the positions. Defaults to range(1, N+1) where N is the number of boxes to be drawn.
The widths of the boxes. The default is 0.5, or 0.15*(distance
between extreme positions), if that is smaller.
If False produces boxes with the Line2D artist. Otherwise, boxes are drawn with Patch artists.
Labels for each dataset (one per dataset).
If True, the tick locations and labels will be adjusted to match the boxplot positions.
When True and the data are distributed such that the 25th and 75th percentiles are equal, whis is set to (0, 100) such that the whisker ends are at the minimum and maximum of the data.
If True (and showmeans is True), will try to render the mean as a line spanning the full width of the box according to meanprops (see below). Not recommended if shownotches is also True. Otherwise, means will be shown as points.
The zorder of the boxplot.
A dictionary mapping each component of the boxplot to a list of the Line2D instances created. That dictionary has the following keys (assuming vertical boxplots):
Show the caps on the ends of whiskers.
Show the central box.
Show the outliers beyond the caps.
Show the arithmetic means.
The style of the caps.
The style of the box.
The style of the whiskers.
The style of the fliers.
The style of the median.
The style of the mean.
If given, all parameters also accept a string s, which is interpreted as data[s] (unless this raises an exception).
See also
Draw an estimate of the probability density function.


Plot a horizontal sequence of rectangles.
A rectangle is drawn for each element of xranges. All rectangles have the same vertical position and size defined by yrange.
This is a convenience function for instantiating a BrokenBarHCollection, adding it to the Axes and autoscaling the view.
The x-positions and extends of the rectangles. For each tuple (xmin, xwidth) a rectangle is drawn from xmin to xmin + xwidth.
The y-position and extend for all the rectangles.
If given, all parameters also accept a string s, which is interpreted as data[s] (unless this raises an exception).
Each kwarg can be either a single argument applying to all rectangles, e.g.:
or a sequence of arguments over which is cycled, e.g.:
would create interleaving black and blue rectangles.
Supported keywords:
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


Label a contour plot.
Adds labels to line contours in given ContourSet.
Line contours to label.
A list of level values, that should be labeled. The list must be a subset of CS.levels. If not given, all levels are labeled.
All other parameters are documented in clabel.
Interactive functions


Set the color limits of the current image.
If either vmin or vmax is None, the image min/max respectively will be used for color scaling.
If you want to set the clim of multiple images, use set_clim on every image, for example:


Close a figure window.
The figure to close. There are a number of ways to specify this:
Pipong
Multipage PDF
Multiprocess
Tight Layout guide


Plot the coherence between x and y.
Plot the coherence between x and y. Coherence is the normalized cross spectral density:
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 blocks.
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 coherence vector.
The frequencies for the elements in Cxy.
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
Bendat & Piersol -- Random Data: Analysis and Measurement Procedures, John Wiley & Sons (1986)


Add a colorbar to a plot.
The matplotlib.cm.ScalarMappable (i.e., AxesImage, ContourSet, etc.) described by this colorbar. This argument is mandatory for the Figure.colorbar method but optional for the pyplot.colorbar function, which sets the default to the current image.
Note that one can create a ScalarMappable "on-the-fly" to generate colorbars not attached to a previously drawn artist, e.g.
Axes into which the colorbar will be drawn.
One or more parent axes from which space for a new colorbar axes will be stolen, if cax is None. This has no effect if cax is set.
If cax is None, a new cax is created as an instance of Axes. If ax is an instance of Subplot and use_gridspec is True, cax is created as an instance of Subplot using the gridspec module.
Additional keyword arguments are of two kinds:
axes properties:
The location, relative to the parent axes, where the colorbar axes is created. It also determines the orientation of the colorbar (colorbars on the left and right are vertical, colorbars at the top and bottom are horizontal). If None, the location will come from the orientation if it is set (vertical colorbars on the right, horizontal ones at the bottom), or default to 'right' if orientation is unset.
The orientation of the colorbar. It is preferable to set the location of the colorbar, as that also determines the orientation; passing incompatible values for location and orientation raises an exception.
Fraction of original axes to use for colorbar.
Fraction by which to multiply the size of the colorbar.
Ratio of long to short dimensions.
Fraction of original axes between colorbar and new image axes.
The anchor point of the colorbar axes. Defaults to (0.0, 0.5) if vertical; (0.5, 1.0) if horizontal.
The anchor point of the colorbar parent axes. If False, the parent axes' anchor will be unchanged. Defaults to (1.0, 0.5) if vertical; (0.5, 0.0) if horizontal.
colorbar properties:
Property
Description
extend
{'neither', 'both', 'min', 'max'} If not 'neither', make pointed end(s) for out-of- range values. These are set for a given colormap using the colormap set_under and set_over methods.
extendfrac
{None, 'auto', length, lengths} If set to None, both the minimum and maximum triangular colorbar extensions with have a length of 5% of the interior colorbar length (this is the default setting). If set to 'auto', makes the triangular colorbar extensions the same lengths as the interior boxes (when spacing is set to 'uniform') or the same lengths as the respective adjacent interior boxes (when spacing is set to 'proportional'). If a scalar, indicates the length of both the minimum and maximum triangular colorbar extensions as a fraction of the interior colorbar length. A two-element sequence of fractions may also be given, indicating the lengths of the minimum and maximum colorbar extensions respectively as a fraction of the interior colorbar length.
extendrect
bool If False the minimum and maximum colorbar extensions will be triangular (the default). If True the extensions will be rectangular.
spacing
{'uniform', 'proportional'} Uniform spacing gives each discrete color the same space; proportional makes the space proportional to the data interval.
ticks
None or list of ticks or Locator If None, ticks are determined automatically from the input.
format
None or str or Formatter If None, ScalarFormatter is used. If a format string is given, e.g., '%.3f', that is used. An alternative Formatter may be given instead.
drawedges
bool Whether to draw lines at color boundaries.
label
str The label on the colorbar's long axis.
The following will probably be useful only in the context of indexed colors (that is, when the mappable has norm=NoNorm()), or other unusual circumstances.
Property
Description
boundaries
None or a sequence
values
None or a sequence which must be of length 1 less than the sequence of boundaries. For each region delimited by adjacent entries in boundaries, the colormapped to the corresponding value in values will be used.
If mappable is a ContourSet, its extend kwarg is included automatically.
The shrink kwarg provides a simple way to scale the colorbar with respect to the axes. Note that if cax is specified, it determines the size of the colorbar and shrink and aspect kwargs are ignored.
For more precise control, you can manually specify the positions of the axes objects in which the mappable and the colorbar are drawn. In this case, do not use any of the axes properties kwargs.
It is known that some vector graphics viewers (svg and pdf) renders white gaps between segments of the colorbar. This is due to bugs in the viewers, not Matplotlib. As a workaround, the colorbar can be rendered with overlapping segments:
However this has negative consequences in other circumstances, e.g. with semi-transparent images (alpha < 1) and colorbar extensions; therefore, this workaround is not used by default (see issue #1188).
Subplots spacings and margins
Ellipse Collection
Axes Divider
Simple Colorbar
Image tutorial
Tight Layout guide


Container for colormaps that are known to Matplotlib by name.
Experimental
While we expect the API to be final, we formally mark it as experimental for 3.5 because we want to keep the option to still adapt the API for 3.6 should the need arise.
The universal registry instance is matplotlib.colormaps. There should be no need for users to instantiate ColormapRegistry themselves.
Read access uses a dict-like interface mapping names to Colormaps:
Returned Colormaps are copies, so that their modification does not change the global definition of the colormap.
Additional colormaps can be added via ColormapRegistry.register:


Bind function func to event s.
One of the following events ids:
The callback function to be executed, which must have the signature:
For the location events (button and key press/release), if the mouse is over the axes, the inaxes attribute of the event will be set to the Axes the event occurs is over, and additionally, the variables xdata and ydata attributes will be set to the mouse location in data coordinates. See KeyEvent and MouseEvent for more info.
A connection id that can be used with FigureCanvasBase.mpl_disconnect.
Mouse move and click events


Plot contour lines.
Call signature:
contour and contourf draw contour lines and filled contours, respectively. Except as noted, function signatures and return values are the same for both versions.
The coordinates of the values in Z.
X and Y must both be 2D with the same shape as Z (e.g. created via numpy.meshgrid), or they must both be 1-D such that len(X) == N is the number of columns in Z and len(Y) == M is the number of rows in Z.
X and Y must both be ordered monotonically.
If not given, they are assumed to be integer indices, i.e. X = range(N), Y = range(M).
The height values over which the contour is drawn.
Determines the number and positions of the contour lines / regions.
If an int n, use MaxNLocator, which tries to automatically choose no more than n+1 "nice" contour levels between vmin and vmax.
If array-like, draw contour lines at the specified levels. The values must be in increasing order.
Enable/disable corner masking, which only has an effect if Z is a masked array. If False, any quad touching a masked point is masked out. If True, only the triangular corners of quads nearest those points are always masked out, other triangular corners comprising three unmasked points are contoured as usual.
The colors of the levels, i.e. the lines for contour and the areas for contourf.
The sequence is cycled for the levels in ascending order. If the sequence is shorter than the number of levels, it's repeated.
As a shortcut, single color strings may be used in place of one-element lists, i.e. 'red' instead of ['red'] to color all levels with the same color. This shortcut does only work for color strings, not for other ways of specifying colors.
By default (value None), the colormap specified by cmap will be used.
The alpha blending value, between 0 (transparent) and 1 (opaque).
A Colormap instance or registered colormap name. The colormap maps the level values to colors.
If both colors and cmap are given, an error is raised.
If a colormap is used, the Normalize instance scales the level values to the canonical colormap range [0, 1] for mapping to colors. If not given, the default linear scaling is used.
If not None, either or both of these values will be supplied to the Normalize instance, overriding the default color scaling based on levels.
Determines the orientation and exact position of Z by specifying the position of Z[0, 0]. This is only relevant, if X, Y are not given.
If origin is not None, then extent is interpreted as in imshow: it gives the outer pixel boundaries. In this case, the position of Z[0, 0] is the center of the pixel, not a corner. If origin is None, then (x0, y0) is the position of Z[0, 0], and (x1, y1) is the position of Z[-1, -1].
This argument is ignored if X and Y are specified in the call to contour.
The locator is used to determine the contour levels if they are not given explicitly via levels. Defaults to MaxNLocator.
Determines the contourf-coloring of values that are outside the levels range.
If 'neither', values outside the levels range are not colored. If 'min', 'max' or 'both', color the values below, above or below and above the levels range.
Values below min(levels) and above max(levels) are mapped to the under/over values of the Colormap. Note that most colormaps do not have dedicated colors for these by default, so that the over and under values are the edge values of the colormap. You may want to set these values explicitly using Colormap.set_under and Colormap.set_over.
Note
An existing QuadContourSet does not get notified if properties of its colormap are changed. Therefore, an explicit call QuadContourSet.changed() is needed after modifying the colormap. The explicit call can be left out, if a colorbar is assigned to the QuadContourSet because it internally calls QuadContourSet.changed().
Example:
Override axis units by specifying an instance of a matplotlib.units.ConversionInterface.
Enable antialiasing, overriding the defaults. For filled contours, the default is True. For line contours, it is taken from rcParams["lines.antialiased"] (default: True).
If 0, no subdivision of the domain. Specify a positive integer to divide the domain into subdomains of nchunk by nchunk quads. Chunking reduces the maximum length of polygons generated by the contouring algorithm which reduces the rendering workload passed on to the backend and also requires slightly less RAM. It can however introduce rendering artifacts at chunk boundaries depending on the backend, the antialiased flag and value of alpha.
Only applies to contour.
The line width of the contour lines.
If a number, all levels will be plotted with this linewidth.
If a sequence, the levels in ascending order will be plotted with the linewidths in the order specified.
If None, this falls back to rcParams["lines.linewidth"] (default: 1.5).
Only applies to contour.
If linestyles is None, the default is 'solid' unless the lines are monochrome. In that case, negative contours will take their linestyle from rcParams["contour.negative_linestyle"] (default: 'dashed') setting.
linestyles can also be an iterable of the above strings specifying a set of linestyles to be used. If this iterable is shorter than the number of contour levels it will be repeated as necessary.
Only applies to contourf.
A list of cross hatch patterns to use on the filled areas. If None, no hatching will be added to the contour. Hatching is supported in the PostScript, PDF, SVG and Agg backends only.
If given, all parameters also accept a string s, which is interpreted as data[s] (unless this raises an exception).
contourf fills intervals that are closed at the top; that is, for boundaries z1 and z2, the filled region is:
except for the lowest interval, which is closed on both sides (i.e. it includes the lowest value).
Interactive functions


Plot filled contours.
Call signature:
contour and contourf draw contour lines and filled contours, respectively. Except as noted, function signatures and return values are the same for both versions.
The coordinates of the values in Z.
X and Y must both be 2D with the same shape as Z (e.g. created via numpy.meshgrid), or they must both be 1-D such that len(X) == N is the number of columns in Z and len(Y) == M is the number of rows in Z.
X and Y must both be ordered monotonically.
If not given, they are assumed to be integer indices, i.e. X = range(N), Y = range(M).
The height values over which the contour is drawn.
Determines the number and positions of the contour lines / regions.
If an int n, use MaxNLocator, which tries to automatically choose no more than n+1 "nice" contour levels between vmin and vmax.
If array-like, draw contour lines at the specified levels. The values must be in increasing order.
Enable/disable corner masking, which only has an effect if Z is a masked array. If False, any quad touching a masked point is masked out. If True, only the triangular corners of quads nearest those points are always masked out, other triangular corners comprising three unmasked points are contoured as usual.
The colors of the levels, i.e. the lines for contour and the areas for contourf.
The sequence is cycled for the levels in ascending order. If the sequence is shorter than the number of levels, it's repeated.
As a shortcut, single color strings may be used in place of one-element lists, i.e. 'red' instead of ['red'] to color all levels with the same color. This shortcut does only work for color strings, not for other ways of specifying colors.
By default (value None), the colormap specified by cmap will be used.
The alpha blending value, between 0 (transparent) and 1 (opaque).
A Colormap instance or registered colormap name. The colormap maps the level values to colors.
If both colors and cmap are given, an error is raised.
If a colormap is used, the Normalize instance scales the level values to the canonical colormap range [0, 1] for mapping to colors. If not given, the default linear scaling is used.
If not None, either or both of these values will be supplied to the Normalize instance, overriding the default color scaling based on levels.
Determines the orientation and exact position of Z by specifying the position of Z[0, 0]. This is only relevant, if X, Y are not given.
If origin is not None, then extent is interpreted as in imshow: it gives the outer pixel boundaries. In this case, the position of Z[0, 0] is the center of the pixel, not a corner. If origin is None, then (x0, y0) is the position of Z[0, 0], and (x1, y1) is the position of Z[-1, -1].
This argument is ignored if X and Y are specified in the call to contour.
The locator is used to determine the contour levels if they are not given explicitly via levels. Defaults to MaxNLocator.
Determines the contourf-coloring of values that are outside the levels range.
If 'neither', values outside the levels range are not colored. If 'min', 'max' or 'both', color the values below, above or below and above the levels range.
Values below min(levels) and above max(levels) are mapped to the under/over values of the Colormap. Note that most colormaps do not have dedicated colors for these by default, so that the over and under values are the edge values of the colormap. You may want to set these values explicitly using Colormap.set_under and Colormap.set_over.
Note
An existing QuadContourSet does not get notified if properties of its colormap are changed. Therefore, an explicit call QuadContourSet.changed() is needed after modifying the colormap. The explicit call can be left out, if a colorbar is assigned to the QuadContourSet because it internally calls QuadContourSet.changed().
Example:
Override axis units by specifying an instance of a matplotlib.units.ConversionInterface.
Enable antialiasing, overriding the defaults. For filled contours, the default is True. For line contours, it is taken from rcParams["lines.antialiased"] (default: True).
If 0, no subdivision of the domain. Specify a positive integer to divide the domain into subdomains of nchunk by nchunk quads. Chunking reduces the maximum length of polygons generated by the contouring algorithm which reduces the rendering workload passed on to the backend and also requires slightly less RAM. It can however introduce rendering artifacts at chunk boundaries depending on the backend, the antialiased flag and value of alpha.
Only applies to contour.
The line width of the contour lines.
If a number, all levels will be plotted with this linewidth.
If a sequence, the levels in ascending order will be plotted with the linewidths in the order specified.
If None, this falls back to rcParams["lines.linewidth"] (default: 1.5).
Only applies to contour.
If linestyles is None, the default is 'solid' unless the lines are monochrome. In that case, negative contours will take their linestyle from rcParams["contour.negative_linestyle"] (default: 'dashed') setting.
linestyles can also be an iterable of the above strings specifying a set of linestyles to be used. If this iterable is shorter than the number of contour levels it will be repeated as necessary.
Only applies to contourf.
A list of cross hatch patterns to use on the filled areas. If None, no hatching will be added to the contour. Hatching is supported in the PostScript, PDF, SVG and Agg backends only.
If given, all parameters also accept a string s, which is interpreted as data[s] (unless this raises an exception).
contourf fills intervals that are closed at the top; that is, for boundaries z1 and z2, the filled region is:
except for the lowest interval, which is closed on both sides (i.e. it includes the lowest value).


Set the colormap to 'cool'.
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 'copper'.
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 cross-spectral density.
The cross spectral density \(P_{xy}\) by Welch's average periodogram method. The vectors x and y are 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 product of the direct FFTs of x and y are averaged over each segment to compute \(P_{xy}\), with a scaling to correct for power loss due to windowing.
If len(x) < NFFT or len(y) < NFFT, they will be zero padded to NFFT.
Arrays or sequences 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 cross spectrum \(P_{xy}\) before scaling (complex valued).
The frequencies corresponding to the elements in Pxy.
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, 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
is equivalent to setting y = x.
For plotting, the power is plotted as \(10 \log_{10}(P_{xy})\) for decibels, though \(P_{xy}\) itself is returned.
Bendat & Piersol -- Random Data: Analysis and Measurement Procedures, John Wiley & Sons (1986)


Remove an Axes (defaulting to the current axes) from its figure.


Disconnect the callback with id cid.
Mouse move and click events


Redraw the current figure.
This is used to update a figure that has been altered, but not automatically re-drawn. If interactive mode is on (via ion()), this should be only rarely needed, but there may be ways to modify the state of a figure without marking it as "stale". Please report these cases as bugs.
This is equivalent to calling fig.canvas.draw_idle(), where fig is the current figure.
Interactive functions
Rotating a 3D plot
Buttons
Check Buttons
Radio Buttons
Textbox


Redraw the current figure if in interactive mode.
Warning
End users will typically not have to call this function because the the interactive mode takes care of this.


Plot y versus x as lines and/or markers with attached errorbars.
x, y define the data locations, xerr, yerr define the errorbar sizes. By default, this draws the data markers/lines as well the errorbars. Use fmt='none' to draw errorbars without any data markers.
The data positions.
The errorbar sizes:
Note that all error arrays should have positive values.
See Different ways of specifying error bars for an example on the usage of xerr and yerr.
The format for the data points / data lines. See plot for details.
Use 'none' (case insensitive) to plot errorbars without any data markers.
The color of the errorbar lines. If None, use the color of the line connecting the markers.
The linewidth of the errorbar lines. If None, the linewidth of the current style is used.
The length of the error bar caps in points.
An alias to the keyword argument markeredgewidth (a.k.a. mew). This setting is a more sensible name for the property that controls the thickness of the error bar cap in points. For backwards compatibility, if mew or markeredgewidth are given, then they will over-ride capthick. This may change in future releases.
If True, will plot the errorbars above the plot symbols. Default is below.
These arguments can be used to indicate that a value gives only upper/lower limits. In that case a caret symbol is used to indicate this. lims-arguments may be scalars, or array-likes of the same length as xerr and yerr. To use limits with inverted axes, set_xlim or set_ylim must be called before errorbar(). Note the tricky parameter names: setting e.g. lolims to True means that the y-value is a lower limit of the True value, so, only an upward-pointing arrow will be drawn!
draws error bars on a subset of the data. errorevery =N draws error bars on the points (x[::N], y[::N]). errorevery =(start, N) draws error bars on the points (x[start::N], y[start::N]). e.g. errorevery=(6, 3) adds error bars to the data at (x[6], x[9], x[12], x[15], ...). Used to avoid overlapping error bars when two series share x-axis values.
The container contains:
If given, the following parameters also accept a string s, which is interpreted as data[s] (unless this raises an exception):
x, y, xerr, yerr
All other keyword arguments are passed on to the plot call drawing the markers. For example, this code makes big red squares with thick green edges:
where mfc, mec, ms and mew are aliases for the longer property names, markerfacecolor, markeredgecolor, markersize and markeredgewidth.
Valid kwargs for the marker properties are 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
Errorbar limit selection


Plot identical parallel lines at the given positions.
This type of plot is commonly used in neuroscience for representing neural events, where it is usually called a spike raster, dot raster, or raster plot.
However, it is useful in any situation where you wish to show the timing or position of multiple sets of discrete events, such as the arrival times of people to a business on each day of the month or the date of hurricanes each year of the last century.
A 1D array-like defines the positions of one sequence of events.
Multiple groups of events may be passed as a list of array-likes. Each group can be styled independently by passing lists of values to lineoffsets, linelengths, linewidths, colors and linestyles.
Note that positions can be a 2D array, but in practice different event groups usually have different counts so that one will use a list of different-length arrays rather than a 2D array.
The direction of the event sequence:
The offset of the center of the lines from the origin, in the direction orthogonal to orientation.
If positions is 2D, this can be a sequence with length matching the length of positions.
The total height of the lines (i.e. the lines stretches from lineoffset - linelength/2 to lineoffset + linelength/2).
If positions is 2D, this can be a sequence with length matching the length of positions.
The line width(s) of the event lines, in points.
If positions is 2D, this can be a sequence with length matching the length of positions.
The color(s) of the event lines.
If positions is 2D, this can be a sequence with length matching the length of positions.
Default is 'solid'. Valid strings are ['solid', 'dashed', 'dashdot', 'dotted', '-', '--', '-.', ':']. Dash tuples should be of the form:
where onoffseq is an even length tuple of on and off ink in points.
If positions is 2D, this can be a sequence with length matching the length of positions.
If given, the following parameters also accept a string s, which is interpreted as data[s] (unless this raises an exception):
positions, lineoffsets, linelengths, linewidths, colors, linestyles
Other keyword arguments are line collection properties. See LineCollection for a list of the valid properties.
The EventCollection that were added.
For linelengths, linewidths, colors, and linestyles, if only a single value is given, that value is applied to all lines. If an array-like is given, it must have the same length as positions, and each value will be applied to the corresponding row of the array.
(Source code, png, pdf)


Add a non-resampled image to the figure.
The image is attached to the lower or upper left corner depending on origin.
The image data. This is an array of one of the following shapes:
The x/y image offset in pixels.
The alpha blending value.
A Normalize instance to map the luminance to the interval [0, 1].
The colormap to use.
If norm is not given, these values set the data limits for the colormap.
Indicates where the [0, 0] index of the array is in the upper left or lower left corner of the axes.
If True, resize the figure to match the given image size.
Additional kwargs are Artist kwargs passed on to FigureImage.
figimage complements the Axes image (imshow) which will be resampled to fit the current Axes. If you want a resampled image to fill the entire figure, you can define an Axes with extent [0, 0, 1, 1].


Place a legend on the figure.
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 Figure.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 all 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.


Return whether the figure with the given id exists.


Add text to figure.
The position to place the text. By default, this is in figure coordinates, floats in [0, 1]. The coordinate system can be changed using the transform keyword.
The text string.
A dictionary to override the default text properties. If not given, the defaults are determined by rcParams["font.*"]. Properties passed as kwargs override the corresponding ones given in fontdict.
Other miscellaneous text parameters.
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
backgroundcolor
color
bbox
dict with properties for patches.FancyBboxPatch
clip_box
unknown
clip_on
unknown
clip_path
unknown
color or c
color
figure
Figure
fontfamily or family
{FONTNAME, 'serif', 'sans-serif', 'cursive', 'fantasy', 'monospace'}
fontproperties or font or font_properties
font_manager.FontProperties or str or pathlib.Path
fontsize or size
float or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'}
fontstretch or stretch
{a numeric value in range 0-1000, 'ultra-condensed', 'extra-condensed', 'condensed', 'semi-condensed', 'normal', 'semi-expanded', 'expanded', 'extra-expanded', 'ultra-expanded'}
fontstyle or style
{'normal', 'italic', 'oblique'}
fontvariant or variant
{'normal', 'small-caps'}
fontweight or weight
{a numeric value in range 0-1000, 'ultralight', 'light', 'normal', 'regular', 'book', 'medium', 'roman', 'semibold', 'demibold', 'demi', 'bold', 'heavy', 'extra bold', 'black'}
gid
str
horizontalalignment or ha
{'center', 'right', 'left'}
in_layout
bool
label
object
linespacing
float (multiple of font size)
math_fontfamily
str
multialignment or ma
{'left', 'right', 'center'}
parse_math
bool
path_effects
AbstractPathEffect
picker
None or bool or float or callable
position
(float, float)
rasterized
bool
rotation
float or {'vertical', 'horizontal'}
rotation_mode
{None, 'default', 'anchor'}
sketch_params
(scale: float, length: float, randomness: float)
snap
bool or None
text
object
transform
Transform
transform_rotates_text
bool
url
str
usetex
bool or None
verticalalignment or va
{'center', 'top', 'bottom', 'baseline', 'center_baseline'}
visible
bool
wrap
bool
x
float
y
float
zorder
float
See also
Fonts demo (object-oriented style)
Fonts demo (keyword arguments)


Create a new figure, or activate an existing figure.
A unique identifier for the figure.
If a figure with that identifier already exists, this figure is made active and returned. An integer refers to the Figure.number attribute, a string refers to the figure label.
If there is no figure with the identifier or num is not given, a new figure is created, made active and returned. If num is an int, it will be used for the Figure.number attribute, otherwise, an auto-generated integer value is used (starting at 1 and incremented for each new figure). If num is a string, the figure label and the window title is set to this value.
Width, height in inches.
The resolution of the figure in dots-per-inch.
The background color.
The border color.
If False, suppress drawing the figure frame.
Optionally use a custom Figure instance.
If True and the figure already exists, then it is cleared.
If False use subplotpars. If True adjust subplot parameters using tight_layout with default padding. When providing a dict containing the keys pad, w_pad, h_pad, and rect, the default tight_layout paddings will be overridden.
If True use constrained layout to adjust positioning of plot elements. Like tight_layout, but designed to be more flexible. See Constrained Layout Guide for examples. (Note: does not work with add_subplot or subplot2grid.)
See Figure for other possible arguments.
The Figure instance returned will also be passed to new_figure_manager in the backends, which allows to hook custom Figure classes into the pyplot interface. Additional kwargs will be passed to the Figure init function.
If you are creating many figures, make sure you explicitly call pyplot.close on the figures you are not using, because this will enable pyplot to properly clean up the memory.
rcParams defines the default values, which can be modified in the matplotlibrc file.
Curve with error band
Errorbar limit selection
EventCollection Demo
Filled polygon
Linestyles
Markevery Demo
prop_cycle property markevery in rcParams
Psd Demo
Scatter plot with histograms
Barcode
Figimage Demo
Layer Images
Streamplot
Aligning Labels
Axes Zoom Effect
Custom Figure subclasses
Resizing axes with constrained layout
Resizing axes with tight layout
Geographic Projections
Using Gridspec to make multi-column/row subplot layouts
Nested Gridspecs
Managing multiple figures in pyplot
Figure subfigures
Creating multiple subplots using plt.subplots
Polar Legend
Scatter plot on polar axis
Arrow Demo
Auto-wrapping text
Text Rotation Mode
The difference between \dfrac and \frac
Annotation arrow style reference
Convert texts to images
Mathtext Examples
Rainbow text
STIX Fonts
Unicode minus
Usetex Baseline Test
Usetex Fonteffects
Annotation Polar
Fig Axes Customize Simple
Simple axes labels
Adding lines to figures
Pyplot Two Subplots
Text Commands
Text Layout
Drawing fancy boxes
Hatch demo
Axes Divider
Demo Axes Grid
Axes Grid2
Showing RGB channels using RGBAxes
Per-row or per-column colorbars
Axes with a fixed physical size
Setting a fixed aspect on ImageGrid cells
Inset Locator Demo
Make Room For Ylabel Using Axesgrid
Parasite Simple2
Simple Axes Divider 1
Simple Axes Divider 3
Simple ImageGrid
Simple ImageGrid 2
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
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
Firefox
Shaded & power normalized rendering
XKCD
The double pendulum problem
Frame grabbing
Rain simulation
Animated 3D random walk
MATPLOTLIB UNCHAINED
Close Event
Interactive functions
Hyperlinks
Matplotlib logo
Multipage PDF
SVG Filter Line
SVG Filter Pie
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
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
Rotating a 3D plot
3D scatterplot
3D plots as subplots
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
Rotating 3D wireframe plot
MRI With EEG
The Sankey class
Long chain of connections using Sankey
Rankine power cycle
SkewT-logP diagram: using transforms and custom projections
Spine Placement
Ellipse With Units
SVG Histogram
Tool Manager
subplot2grid demo
GridSpec demo
Nested GridSpecs
Simple Legend01
Menu
Rectangle and ellipse selectors
Basic Usage
Pyplot tutorial
Image tutorial
Artist tutorial
Constrained Layout Guide
Tight Layout guide
Arranging multiple Axes in a Figure
origin and extent in imshow
Path effects guide
Transformations Tutorial
Specifying Colors
Complex and semantic figure composition
Text in Matplotlib Plots
Text properties and layout


Plot filled polygons.
Each polygon is defined by the lists of x and y positions of its nodes, optionally followed by a color specifier. See matplotlib.colors for supported color specifiers. The standard color cycle is used for polygons without a color specifier.
You can plot multiple polygons by providing multiple x, y, [color] groups.
For example, each of the following is legal:
An object with labelled data. If given, provide the label names to plot in x and y, e.g.:
Use fill_between() if you would like to fill the region between two curves.
Filled polygon
Interactive functions
Fill Spiral


Fill the area between two horizontal curves.
The curves are defined by the points (x, y1) and (x, y2). This creates one or multiple polygons describing the filled area.
You may exclude some horizontal sections from filling using where.
By default, the edges connect the given points directly. Use step if the filling should be a step function, i.e. constant in between x.
The x coordinates of the nodes defining the curves.
The y coordinates of the nodes defining the first curve.
The y coordinates of the nodes defining the second curve.
Define where to exclude some horizontal regions from being filled. The filled regions are defined by the coordinates x[where]. More precisely, fill between x[i] and x[i+1] if where[i] and where[i+1]. Note that this definition implies that an isolated True value between two False values in where will not result in filling. Both sides of the True position remain unfilled due to the adjacent False values.
This option is only relevant if where is used and the two curves are crossing each other.
Semantically, where is often used for y1 > y2 or similar. By default, the nodes of the polygon defining the filled region will only be placed at the positions in the x array. Such a polygon cannot describe the above semantics close to the intersection. The x-sections containing the intersection are simply clipped.
Setting interpolate to True will calculate the actual intersection point and extend the filled region up to this point.
Define step if the filling should be a step function, i.e. constant in between x. The value determines where the step will occur:
A PolyCollection containing the plotted polygons.
If given, the following parameters also accept a string s, which is interpreted as data[s] (unless this raises an exception):
x, y1, y2, where
All other keyword arguments are passed on to PolyCollection. They control the Polygon 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
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
Fill between two sets of y-values.
Fill between two sets of x-values.


Fill the area between two vertical curves.
The curves are defined by the points (y, x1) and (y, x2). This creates one or multiple polygons describing the filled area.
You may exclude some vertical sections from filling using where.
By default, the edges connect the given points directly. Use step if the filling should be a step function, i.e. constant in between y.
The y coordinates of the nodes defining the curves.
The x coordinates of the nodes defining the first curve.
The x coordinates of the nodes defining the second curve.
Define where to exclude some vertical regions from being filled. The filled regions are defined by the coordinates y[where]. More precisely, fill between y[i] and y[i+1] if where[i] and where[i+1]. Note that this definition implies that an isolated True value between two False values in where will not result in filling. Both sides of the True position remain unfilled due to the adjacent False values.
This option is only relevant if where is used and the two curves are crossing each other.
Semantically, where is often used for x1 > x2 or similar. By default, the nodes of the polygon defining the filled region will only be placed at the positions in the y array. Such a polygon cannot describe the above semantics close to the intersection. The y-sections containing the intersection are simply clipped.
Setting interpolate to True will calculate the actual intersection point and extend the filled region up to this point.
Define step if the filling should be a step function, i.e. constant in between y. The value determines where the step will occur:
A PolyCollection containing the plotted polygons.
If given, the following parameters also accept a string s, which is interpreted as data[s] (unless this raises an exception):
y, x1, x2, where
All other keyword arguments are passed on to PolyCollection. They control the Polygon 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
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
Fill between two sets of y-values.
Fill between two sets of x-values.


Find artist objects.
Recursively find all Artist instances contained in the artist.
A filter criterion for the matches. This can be
Include self in the list to be checked for a match.


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


Get the current Axes.
If there is currently no Axes on this Figure, a new one is created using Figure.add_subplot. (To test whether there is currently an Axes on a Figure, check whether figure.axes is empty. To test whether there is currently a Figure on the pyplot figure stack, check whether pyplot.get_fignums() is empty.)
The following kwargs are supported for ensuring the returned Axes adheres to the given projection etc., and for Axes creation if the active Axes does not exist:
Property
Description
adjustable
{'box', 'datalim'}
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
anchor
(float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', ...}
animated
bool
aspect
{'auto', 'equal'} or float
autoscale_on
bool
autoscalex_on
bool
autoscaley_on
bool
axes_locator
Callable[[Axes, Renderer], Bbox]
axisbelow
bool or 'line'
box_aspect
float or None
clip_box
Bbox
clip_on
bool
clip_path
Patch or (Path, Transform) or None
facecolor or fc
color
figure
Figure
frame_on
bool
gid
str
in_layout
bool
label
object
navigate
bool
navigate_mode
unknown
path_effects
AbstractPathEffect
picker
None or bool or float or callable
position
[left, bottom, width, height] or Bbox
prop_cycle
unknown
rasterization_zorder
float or None
rasterized
bool
sketch_params
(scale: float, length: float, randomness: float)
snap
bool or None
title
str
transform
Transform
url
str
visible
bool
xbound
unknown
xlabel
str
xlim
(bottom: float, top: float)
xmargin
float greater than -0.5
xscale
{"linear", "log", "symlog", "logit", ...} or ScaleBase
xticklabels
unknown
xticks
unknown
ybound
unknown
ylabel
str
ylim
(bottom: float, top: float)
ymargin
float greater than -0.5
yscale
{"linear", "log", "symlog", "logit", ...} or ScaleBase
yticklabels
unknown
yticks
unknown
zorder
float
Creating annotated heatmaps
Managing multiple figures in pyplot
Scale invariant angle label
Rainbow text
Infinite lines
Set and get properties
Hinton diagrams
Tight Layout guide


Get the current figure.
If there is currently no figure on the pyplot figure stack, a new one is created using figure(). (To test whether there is currently a figure on the pyplot figure stack, check whether get_fignums() is empty.)


Get the current colorable artist.
Specifically, returns the current ScalarMappable instance (Image created by imshow or figimage, Collection created by pcolor or scatter, etc.), or None if no such instance has been defined.
The current image is an attribute of the current Axes, or the nearest earlier Axes in the current figure that contains an image.
Historically, the only colorable artists were images; hence the name gci (get current image).


Return the value of an Artist's property, or print all of them.
The queried artist; e.g., a Line2D, a Text, or an Axes.
If property is 'somename', this function returns obj.get_somename().
If it's None (or unset), it prints all gettable properties from obj. Many properties have aliases for shorter typing, e.g. 'lw' is an alias for 'linewidth'. In the output, aliases and full property names will be listed as:
property or alias = value
e.g.:
linewidth or lw = 2
See also


Return the figure manager of the current figure.
The figure manager is a container for the actual backend-depended window that displays the figure on screen.
If no current figure exists, a new one is created, and its figure manager is returned.


Return a list of existing figure labels.


Return a list of existing figure numbers.


Get a sorted list of all of the plotting commands.


Return the value of an Artist's property, or print all of them.
The queried artist; e.g., a Line2D, a Text, or an Axes.
If property is 'somename', this function returns obj.get_somename().
If it's None (or unset), it prints all gettable properties from obj. Many properties have aliases for shorter typing, e.g. 'lw' is an alias for 'linewidth'. In the output, aliases and full property names will be listed as:
property or alias = value
e.g.:
linewidth or lw = 2
See also
Set and get properties
Artist tutorial


Blocking call to interact with a figure.
Wait until the user clicks n times on the figure, and return the coordinates of each click in a list.
There are three possible interactions:
The actions are assigned to mouse buttons via the arguments mouse_add, mouse_pop and mouse_stop.
Number of mouse clicks to accumulate. If negative, accumulate clicks until the input is terminated manually.
Number of seconds to wait before timing out. If zero or negative will never timeout.
If True, show a red cross at the location of each click.
Mouse button used to add points.
Mouse button used to remove the most recently added point.
Mouse button used to stop input.
A list of the clicked (x, y) coordinates.
The keyboard can also be used to select points in case your mouse does not have one or more of the buttons. The delete and backspace keys act like right clicking (i.e., remove last point), the enter key terminates input and any other key (not already used by the window manager) selects a point.
Interactive functions


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


Configure the grid lines.
Whether to show the grid lines. If any kwargs are supplied, it is assumed you want the grid on and visible will be set to True.
If visible is None and there are no kwargs, this toggles the visibility of the lines.
The grid lines to apply the changes on.
The axis to apply the changes on.
Define the line properties of the grid, e.g.:
Valid keyword arguments are:
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
The axis is drawn as a unit, so the effective zorder for drawing the grid is determined by the zorder of each axis, not by the zorder of the Line2D objects comprising the grid. Therefore, to set grid zorder, use set_axisbelow or, for more control, call the set_zorder method of each axis.
Step Demo
Geographic Projections
Pyplot Text
Customize Rc
Findobj Demo
Custom scale
SkewT-logP diagram: using transforms and custom projections
Pyplot tutorial


Make a 2D hexagonal binning plot of points x, y.
If C is None, the value of the hexagon is determined by the number of points in the hexagon. Otherwise, C specifies values at the coordinate (x[i], y[i]). For each hexagon, these values are reduced using reduce_C_function.
The data positions. x and y must be of the same length.
If given, these values are accumulated in the bins. Otherwise, every point has a value of 1. Must be of the same length as x and y.
If a single int, the number of hexagons in the x-direction. The number of hexagons in the y-direction is chosen such that the hexagons are approximately regular.
Alternatively, if a tuple (nx, ny), the number of hexagons in the x-direction and the y-direction.
Discretization of the hexagon values.
Use a linear or log10 scale on the horizontal axis.
Use a linear or log10 scale on the vertical axis.
If not None, only display cells with more than mincnt number of points in the cell.
If marginals is True, plot the marginal density as colormapped rectangles along the bottom of the x-axis and left of the y-axis.
The limits of the bins (xmin, xmax, ymin, ymax). The default assigns the limits based on gridsize, x, y, xscale and yscale.
If xscale or yscale is set to 'log', the limits are expected to be the exponent for a power of 10. E.g. for x-limits of 1 and 50 in 'linear' scale and y-limits of 10 and 1000 in 'log' scale, enter (1, 50, 1, 3).
A PolyCollection defining the hexagonal bins.
If marginals is True, horizontal bar and vertical bar (both PolyCollections) will be attached to the return collection as attributes hbar and vbar.
The Colormap instance or registered colormap name used to map the bin values to colors.
The Normalize instance scales the bin 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 the bins in case of the default linear scaling). It is an error to use vmin/vmax when norm is given.
The alpha blending value, between 0 (transparent) and 1 (opaque).
If None, defaults to 1.0.
The color of the hexagon edges. Possible values are:
The function to aggregate C within the bins. It is ignored if C is not given. This must have the signature:
Commonly used functions are:
If given, the following parameters also accept a string s, which is interpreted as data[s] (unless this raises an exception):
x, y, C
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
2D histogram rectangular bins


Plot a histogram.
Compute and draw the histogram of x. The return value is a tuple (n, bins, patches) or ([n0, n1, ...], bins, [patches0, patches1, ...]) if the input contains multiple data. See the documentation of the weights parameter to draw a histogram of already-binned data.
Multiple data can be provided via x as a list of datasets of potentially different length ([x0, x1, ...]), or as a 2D ndarray in which each column is a dataset. Note that the ndarray form is transposed relative to the list form.
Masked arrays are not supported.
The bins, range, weights, and density parameters behave as in numpy.histogram.
Input values, this takes either a single array or a sequence of arrays which are not required to be of the same length.
If bins is an integer, it defines the number of equal-width bins in the range.
If bins is a sequence, it defines the bin edges, including the left edge of the first bin and the right edge of the last bin; in this case, bins may be unequally spaced. All but the last (righthand-most) bin is half-open. In other words, if bins is:
then the first bin is [1, 2) (including 1, but excluding 2) and the second [2, 3). The last bin, however, is [3, 4], which includes 4.
If bins is a string, it is one of the binning strategies supported by numpy.histogram_bin_edges: 'auto', 'fd', 'doane', 'scott', 'stone', 'rice', 'sturges', or 'sqrt'.
The lower and upper range of the bins. Lower and upper outliers are ignored. If not provided, range is (x.min(), x.max()). Range has no effect if bins is a sequence.
If bins is a sequence or range is specified, autoscaling is based on the specified bin range instead of the range of x.
If True, draw and return a probability density: each bin will display the bin's raw count divided by the total number of counts and the bin width (density = counts / (sum(counts) * np.diff(bins))), so that the area under the histogram integrates to 1 (np.sum(density * np.diff(bins)) == 1).
If stacked is also True, the sum of the histograms is normalized to 1.
An array of weights, of the same shape as x. Each value in x only contributes its associated weight towards the bin count (instead of 1). If density is True, the weights are normalized, so that the integral of the density over the range remains 1.
This parameter can be used to draw a histogram of data that has already been binned, e.g. using numpy.histogram (by treating each bin as a single point with a weight equal to its count)
(or you may alternatively use bar()).
If True, then a histogram is computed where each bin gives the counts in that bin plus all bins for smaller values. The last bin gives the total number of datapoints.
If density is also True then the histogram is normalized such that the last bin equals 1.
If cumulative is a number less than 0 (e.g., -1), the direction of accumulation is reversed. In this case, if density is also True, then the histogram is normalized such that the first bin equals 1.
Location of the bottom of each bin, ie. bins are drawn from bottom to bottom + hist(x, bins) If a scalar, the bottom of each bin is shifted by the same amount. If an array, each bin is shifted independently and the length of bottom must match the number of bins. If None, defaults to 0.
The type of histogram to draw.
The horizontal alignment of the histogram bars.
If 'horizontal', barh will be used for bar-type histograms and the bottom kwarg will be the left edges.
The relative width of the bars as a fraction of the bin width. If None, automatically compute the width.
Ignored if histtype is 'step' or 'stepfilled'.
If True, the histogram axis will be set to a log scale.
Color or sequence of colors, one per dataset. Default (None) uses the standard line color sequence.
String, or sequence of strings to match multiple datasets. Bar charts yield multiple patches per dataset, but only the first gets the label, so that legend will work as expected.
If True, multiple data are stacked on top of each other If False multiple data are arranged side by side if histtype is 'bar' or on top of each other if histtype is 'step'
The values of the histogram bins. See density and weights for a description of the possible semantics. If input x is an array, then this is an array of length nbins. If input is a sequence of arrays [data1, data2, ...], then this is a list of arrays with the values of the histograms for each of the arrays in the same order. The dtype of the array n (or of its element arrays) will always be float even if no weighting or normalization is used.
The edges of the bins. Length nbins + 1 (nbins left edges and right edge of last bin). Always a single array even when multiple data sets are passed in.
Container of individual artists used to create the histogram or list of such containers if there are multiple input datasets.
If given, the following parameters also accept a string s, which is interpreted as data[s] (unless this raises an exception):
x, weights
Patch properties
See also
2D histogram with rectangular bins
2D histogram with hexagonal bins
For large numbers of bins (>1000), 'step' and 'stepfilled' can be significantly faster than 'bar' and 'barstacked'.
Pyplot Text
Animated histogram
SVG Histogram
Pyplot tutorial
Image tutorial


Make a 2D histogram plot.
Input values
The bin specification:
The default value is 10.
The leftmost and rightmost edges of the bins along each dimension (if not specified explicitly in the bins parameters): [[xmin,
xmax], [ymin, ymax]]. All values outside of this range will be considered outliers and not tallied in the histogram.
Normalize histogram. See the documentation for the density parameter of hist for more details.
An array of values w_i weighing each sample (x_i, y_i).
All bins that has count less than cmin or more than cmax will not be displayed (set to NaN before passing to imshow) and these count values in the return value count histogram will also be set to nan upon return.
The bi-dimensional histogram of samples x and y. Values in x are histogrammed along the first dimension and values in y are histogrammed along the second dimension.
The bin edges along the x axis.
The bin edges along the y axis.
A colors.Colormap instance. If not set, use rc settings.
A colors.Normalize instance is used to scale luminance data to [0, 1]. If not set, defaults to colors.Normalize().
Arguments passed to the Normalize instance.
The alpha blending value.
If given, the following parameters also accept a string s, which is interpreted as data[s] (unless this raises an exception):
x, y, weights
Additional parameters are passed along to the pcolormesh method and QuadMesh constructor.
See also
1D histogram plotting
2D histogram with hexagonal bins


Plot horizontal lines at each y from xmin to xmax.
y-indexes where to plot the lines.
Respective beginning and end of each line. If scalars are provided, all lines will have same length.
If given, the following parameters also accept a string s, which is interpreted as data[s] (unless this raises an exception):
y, xmin, xmax, colors
See also
vertical lines
horizontal line across the Axes


Set the colormap to 'hot'.
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 'hsv'.
This changes the default colormap as well as the colormap of the current image if there is one. See help(colormaps) for more information.


Read an image from a file into an array.
Note
This function exists for historical reasons. It is recommended to use PIL.Image.open instead for loading images.
The image file to read: a filename, a URL or a file-like object opened in read-binary mode.
Passing a URL is deprecated. Please open the URL for reading and pass the result to Pillow, e.g. with np.array(PIL.Image.open(urllib.request.urlopen(url))).
The image file format assumed for reading the data. The image is loaded as a PNG file if format is set to "png", if fname is a path or opened file with a ".png" extension, or if it is an URL. In all other cases, format is ignored and the format is auto-detected by PIL.Image.open.
The image data. The returned array has shape
PNG images are returned as float arrays (0-1). All other formats are returned as int arrays, with a bit depth determined by the file's contents.
Clipping images with patches
Image Demo
AnnotationBbox demo
Using a text as a Path
Convert texts to images
Ribbon Box


Save an array as an image file.
A path or a file-like object to store the image in. If format is not set, then the output format is inferred from the extension of fname, if any, and from rcParams["savefig.format"] (default: 'png') otherwise. If format is set, it determines the output format.
The image data. The shape can be one of MxN (luminance), MxNx3 (RGB) or MxNx4 (RGBA).
vmin and vmax set the color scaling for the image by fixing the values that map to the colormap color limits. If either vmin or vmax is None, that limit is determined from the arr min/max value.
A Colormap instance or registered colormap name. The colormap maps scalar data to colors. It is ignored for RGB(A) data.
The file format, e.g. 'png', 'pdf', 'svg', ... The behavior when this is unset is documented under fname.
Indicates whether the (0, 0) index of the array is in the upper left or lower left corner of the axes.
The DPI to store in the metadata of the file. This does not affect the resolution of the output image. Depending on file format, this may be rounded to the nearest integer.
Metadata in the image file. The supported keys depend on the output format, see the documentation of the respective backends for more information.
Keyword arguments passed to PIL.Image.Image.save. If the 'pnginfo' key is present, it completely overrides metadata, including the default 'Software' key.


Display data as an image, i.e., on a 2D regular raster.
The input may either be actual RGB(A) data, or 2D scalar data, which will be rendered as a pseudocolor image. For displaying a grayscale image set up the colormapping using the parameters cmap='gray', vmin=0, vmax=255.
The number of pixels used to render an image is set by the Axes size and the dpi of the figure. This can lead to aliasing artifacts when the image is resampled because the displayed image size will usually not match the size of X (see Image antialiasing). The resampling can be controlled via the interpolation parameter and/or rcParams["image.interpolation"] (default: 'antialiased').
The image data. Supported array shapes are:
The first two dimensions (M, N) define the rows and columns of the image.
Out-of-range RGB(A) values are clipped.
The Colormap instance or registered colormap name used to map scalar data to colors. This parameter is ignored for RGB(A) data.
The Normalize instance used to scale scalar data to the [0, 1] range before mapping to colors using cmap. By default, a linear scaling mapping the lowest value to 0 and the highest to 1 is used. This parameter is ignored for RGB(A) data.
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.
The interpolation method used.
Supported values are 'none', 'antialiased', 'nearest', 'bilinear', 'bicubic', 'spline16', 'spline36', 'hanning', 'hamming', 'hermite', 'kaiser', 'quadric', 'catrom', 'gaussian', 'bessel', 'mitchell', 'sinc', 'lanczos', 'blackman'.
If interpolation is 'none', then no interpolation is performed on the Agg, ps, pdf and svg backends. Other backends will fall back to 'nearest'. Note that most SVG renderers perform interpolation at rendering and that the default interpolation method they implement may differ.
If interpolation is the default 'antialiased', then 'nearest' interpolation is used if the image is upsampled by more than a factor of three (i.e. the number of display pixels is at least three times the size of the data array). If the upsampling rate is smaller than 3, or the image is downsampled, then 'hanning' interpolation is used to act as an anti-aliasing filter, unless the image happens to be upsampled by exactly a factor of two or one.
See Interpolations for imshow for an overview of the supported interpolation methods, and Image antialiasing for a discussion of image antialiasing.
Some interpolation methods require an additional radius parameter, which can be set by filterrad. Additionally, the antigrain image resize filter is controlled by the parameter filternorm.
If 'data', interpolation is carried out on the data provided by the user. If 'rgba', the interpolation is carried out after the colormapping has been applied (visual interpolation).
The alpha blending value, between 0 (transparent) and 1 (opaque). If alpha is an array, the alpha blending values are applied pixel by pixel, and alpha must have the same shape as X.
When using scalar data and no explicit norm, vmin and vmax define the data range that the colormap covers. By default, the colormap covers the complete value range of the supplied data. It is an error to use vmin/vmax when norm is given. When using RGB(A) data, parameters vmin/vmax are ignored.
Place the [0, 0] index of the array in the upper left or lower left corner of the Axes. The convention (the default) 'upper' is typically used for matrices and images.
Note that the vertical axis points upward for 'lower' but downward for 'upper'.
See the origin and extent in imshow tutorial for examples and a more detailed description.
The bounding box in data coordinates that the image will fill. The image is stretched individually along x and y to fill the box.
The default extent is determined by the following conditions. Pixels have unit size in data coordinates. Their centers are on integer coordinates, and their center coordinates range from 0 to columns-1 horizontally and from 0 to rows-1 vertically.
Note that the direction of the vertical axis and thus the default values for top and bottom depend on origin:
See the origin and extent in imshow tutorial for examples and a more detailed description.
A parameter for the antigrain image resize filter (see the antigrain documentation). If filternorm is set, the filter normalizes integer values and corrects the rounding errors. It doesn't do anything with the source floating point values, it corrects only integers according to the rule of 1.0 which means that any sum of pixel weights must be equal to 1.0. So, the filter function must produce a graph of the proper shape.
The filter radius for filters that have a radius parameter, i.e. when interpolation is one of: 'sinc', 'lanczos' or 'blackman'.
When True, use a full resampling method. When False, only resample when the output image is larger than the input image.
Set the url of the created AxesImage. See Artist.set_url.
If given, all parameters also accept a string s, which is interpreted as data[s] (unless this raises an exception).
These parameters are passed on to the constructor of the AxesImage artist.
See also
Plot a matrix or an array as an image.
Unless extent is used, pixel centers will be located at integer coordinates. In other words: the origin will coincide with the center of pixel (0, 0).
There are two common representations for RGB images with an alpha channel:
imshow expects RGB images adopting the straight (unassociated) alpha representation.
Layer Images
Subplots spacings and margins
Dolphins
Hyperlinks
Image tutorial
Tight Layout guide


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


Install a repl display hook so that any stale figure are automatically redrawn when control is returned to the repl.
This works both with IPython and with vanilla python shells.


Disable interactive mode.
See pyplot.isinteractive for more details.
See also
Enable interactive mode.
Whether interactive mode is enabled.
Show all figures (and maybe block).
Show all figures, and block for a time.
For a temporary change, this can be used as a context manager:
To enable usage as a context manager, this function returns an _IoffContext object. The return value is not intended to be stored or accessed by the user.


Enable interactive mode.
See pyplot.isinteractive for more details.
See also
Disable interactive mode.
Whether interactive mode is enabled.
Show all figures (and maybe block).
Show all figures, and block for a time.
For a temporary change, this can be used as a context manager:
To enable usage as a context manager, this function returns an _IonContext object. The return value is not intended to be stored or accessed by the user.


Return whether plots are updated after every plotting command.
The interactive mode is mainly useful if you build plots from the command line and want to see the effect of each command while you are building the figure.
In interactive mode:
In non-interactive mode:
See also
Enable interactive mode.
Disable interactive mode.
Show all figures (and maybe block).
Show all figures, and block for a time.


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