matplotlib.pyplot.colorbar   matplotlib.pyplot.colorbar(mappable=None, cax=None, ax=None, **kw)[source]

Add a colorbar to a plot.  Parameters
 mappable

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. fig.colorbar(cm.ScalarMappable(norm=norm, cmap=cmap), ax=ax)

caxAxes, optional

Axes into which the colorbar will be drawn.
axAxes, list of Axes, optional

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.
use_gridspecbool, optional

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.    Returns

colorbarColorbar

   Notes Additional keyword arguments are of two kinds: axes properties:  locationNone or {'left', 'right', 'top', 'bottom'}

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.  orientationNone or {'vertical', 'horizontal'}

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.  fractionfloat, default: 0.15

Fraction of original axes to use for colorbar.  shrinkfloat, default: 1.0

Fraction by which to multiply the size of the colorbar.  aspectfloat, default: 20

Ratio of long to short dimensions.  padfloat, default: 0.05 if vertical, 0.15 if horizontal

Fraction of original axes between colorbar and new image axes.  anchor(float, float), optional

The anchor point of the colorbar axes. Defaults to (0.0, 0.5) if vertical; (0.5, 1.0) if horizontal.  panchor(float, float), or False, optional

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: cbar = colorbar()
cbar.solids.set_edgecolor("face")
draw()
 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).
  Examples using matplotlib.pyplot.colorbar

   Subplots spacings and margins

   Ellipse Collection

   Axes Divider

   Simple Colorbar

   Image tutorial

   Tight Layout guide


matplotlib.pyplot.colormaps[source]

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: import matplotlib as mpl
cmap = mpl.colormaps['viridis']
 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: mpl.colormaps.register(my_colormap)


matplotlib.pyplot.connect   matplotlib.pyplot.connect(s, func)[source]

Bind function func to event s.  Parameters

sstr

One of the following events ids:  'button_press_event' 'button_release_event' 'draw_event' 'key_press_event' 'key_release_event' 'motion_notify_event' 'pick_event' 'resize_event' 'scroll_event' 'figure_enter_event', 'figure_leave_event', 'axes_enter_event', 'axes_leave_event' 'close_event'.
funccallable

The callback function to be executed, which must have the signature: def func(event: Event) -> Any
 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.    Returns
 cid

A connection id that can be used with FigureCanvasBase.mpl_disconnect.     Examples def on_press(event):
    print('you pressed', event.button, event.xdata, event.ydata)

cid = canvas.mpl_connect('button_press_event', on_press)

  Examples using matplotlib.pyplot.connect

   Mouse move and click events


matplotlib.pyplot.contour   matplotlib.pyplot.contour(*args, data=None, **kwargs)[source]

Plot contour lines. Call signature: contour([X, Y,] Z, [levels], **kwargs)
 contour and contourf draw contour lines and filled contours, respectively. Except as noted, function signatures and return values are the same for both versions.  Parameters

X, Yarray-like, optional

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).
Z(M, N) array-like

The height values over which the contour is drawn.
levelsint or array-like, optional

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.    Returns
 QuadContourSet
  Other Parameters

corner_maskbool, default: rcParams["contour.corner_mask"] (default: True)

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.
colorscolor string or sequence of colors, optional

The colors of the levels, i.e. the lines for contour and the areas for contourf. The sequence is cycled for the levels in ascending order. If the sequence is shorter than the number of levels, it's repeated. As a shortcut, 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.
alphafloat, default: 1

The alpha blending value, between 0 (transparent) and 1 (opaque).
cmapstr or Colormap, default: rcParams["image.cmap"] (default: 'viridis')

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.
normNormalize, optional

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.
vmin, vmaxfloat, optional

If not None, either or both of these values will be supplied to the Normalize instance, overriding the default color scaling based on levels.
origin{None, 'upper', 'lower', 'image'}, default: None

Determines the orientation and exact position of Z by specifying the position of Z[0, 0]. This is only relevant, if X, Y are not given.
None: Z[0, 0] is at X=0, Y=0 in the lower left corner. 'lower': Z[0, 0] is at X=0.5, Y=0.5 in the lower left corner. 'upper': Z[0, 0] is at X=N+0.5, Y=0.5 in the upper left corner. 'image': Use the value from rcParams["image.origin"] (default: 'upper').
extent(x0, x1, y0, y1), optional

If origin is not None, then extent is interpreted as in imshow: it gives the outer pixel boundaries. In this case, the position of Z[0, 0] is the center of the pixel, not a corner. If origin is None, then (x0, y0) is the position of Z[0, 0], and (x1, y1) is the position of Z[-1, -1]. This argument is ignored if X and Y are specified in the call to contour.
locatorticker.Locator subclass, optional

The locator is used to determine the contour levels if they are not given explicitly via levels. Defaults to MaxNLocator.
extend{'neither', 'both', 'min', 'max'}, default: 'neither'

Determines the contourf-coloring of values that are outside the levels range. If 'neither', values outside the levels range are not colored. If 'min', 'max' or 'both', color the values below, above or below and above the levels range. Values below min(levels) and 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: x = np.arange(1, 10)
y = x.reshape(-1, 1)
h = x * y

cs = plt.contourf(h, levels=[10, 30, 50],
    colors=['#808080', '#A0A0A0', '#C0C0C0'], extend='both')
cs.cmap.set_over('red')
cs.cmap.set_under('blue')
cs.changed()

xunits, yunitsregistered units, optional

Override axis units by specifying an instance of a matplotlib.units.ConversionInterface.
antialiasedbool, optional

Enable antialiasing, overriding the defaults. For filled contours, the default is True. For line contours, it is taken from rcParams["lines.antialiased"] (default: True).
nchunkint >= 0, optional

If 0, no subdivision of the domain. Specify a positive integer to divide the domain into subdomains of nchunk by nchunk quads. Chunking reduces the maximum length of polygons generated by the contouring algorithm which reduces the rendering workload passed on to the backend and also requires slightly less RAM. It can however introduce rendering artifacts at chunk boundaries depending on the backend, the antialiased flag and value of alpha.
linewidthsfloat or array-like, default: rcParams["contour.linewidth"] (default: None)

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).
linestyles{None, 'solid', 'dashed', 'dashdot', 'dotted'}, optional

Only applies to contour. If linestyles is None, the default is 'solid' unless the lines are monochrome. In that case, negative contours will 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.
hatcheslist[str], optional

Only applies to contourf. A list of cross hatch patterns to use on the filled areas. If None, no hatching will be added to the contour. Hatching is supported in the PostScript, PDF, SVG and Agg backends only.
dataindexable object, optional

If given, all parameters also accept a string s, which is interpreted as data[s] (unless this raises an exception).     Notes
contourf differs from the MATLAB version in that it does not draw the polygon edges. To draw edges, add line contours with calls to contour.
contourf fills intervals that are closed at the top; that is, for boundaries z1 and z2, the filled region is: z1 < Z <= z2
 except for the lowest interval, which is closed on both sides (i.e. it includes the lowest value).
contour and contourf use a marching squares algorithm to compute contour locations. More information can be found in the source src/_contour.h.
  Examples using matplotlib.pyplot.contour

   Interactive functions


matplotlib.pyplot.contourf   matplotlib.pyplot.contourf(*args, data=None, **kwargs)[source]

Plot filled contours. Call signature: contourf([X, Y,] Z, [levels], **kwargs)
 contour and contourf draw contour lines and filled contours, respectively. Except as noted, function signatures and return values are the same for both versions.  Parameters

X, Yarray-like, optional

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).
Z(M, N) array-like

The height values over which the contour is drawn.
levelsint or array-like, optional

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.    Returns
 QuadContourSet
  Other Parameters

corner_maskbool, default: rcParams["contour.corner_mask"] (default: True)

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.
colorscolor string or sequence of colors, optional

The colors of the levels, i.e. the lines for contour and the areas for contourf. The sequence is cycled for the levels in ascending order. If the sequence is shorter than the number of levels, it's repeated. As a shortcut, 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.
alphafloat, default: 1

The alpha blending value, between 0 (transparent) and 1 (opaque).
cmapstr or Colormap, default: rcParams["image.cmap"] (default: 'viridis')

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.
normNormalize, optional

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.
vmin, vmaxfloat, optional

If not None, either or both of these values will be supplied to the Normalize instance, overriding the default color scaling based on levels.
origin{None, 'upper', 'lower', 'image'}, default: None

Determines the orientation and exact position of Z by specifying the position of Z[0, 0]. This is only relevant, if X, Y are not given.
None: Z[0, 0] is at X=0, Y=0 in the lower left corner. 'lower': Z[0, 0] is at X=0.5, Y=0.5 in the lower left corner. 'upper': Z[0, 0] is at X=N+0.5, Y=0.5 in the upper left corner. 'image': Use the value from rcParams["image.origin"] (default: 'upper').
extent(x0, x1, y0, y1), optional

If origin is not None, then extent is interpreted as in imshow: it gives the outer pixel boundaries. In this case, the position of Z[0, 0] is the center of the pixel, not a corner. If origin is None, then (x0, y0) is the position of Z[0, 0], and (x1, y1) is the position of Z[-1, -1]. This argument is ignored if X and Y are specified in the call to contour.
locatorticker.Locator subclass, optional

The locator is used to determine the contour levels if they are not given explicitly via levels. Defaults to MaxNLocator.
extend{'neither', 'both', 'min', 'max'}, default: 'neither'

Determines the contourf-coloring of values that are outside the levels range. If 'neither', values outside the levels range are not colored. If 'min', 'max' or 'both', color the values below, above or below and above the levels range. Values below min(levels) and 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: x = np.arange(1, 10)
y = x.reshape(-1, 1)
h = x * y

cs = plt.contourf(h, levels=[10, 30, 50],
    colors=['#808080', '#A0A0A0', '#C0C0C0'], extend='both')
cs.cmap.set_over('red')
cs.cmap.set_under('blue')
cs.changed()

xunits, yunitsregistered units, optional

Override axis units by specifying an instance of a matplotlib.units.ConversionInterface.
antialiasedbool, optional

Enable antialiasing, overriding the defaults. For filled contours, the default is True. For line contours, it is taken from rcParams["lines.antialiased"] (default: True).
nchunkint >= 0, optional

If 0, no subdivision of the domain. Specify a positive integer to divide the domain into subdomains of nchunk by nchunk quads. Chunking reduces the maximum length of polygons generated by the contouring algorithm which reduces the rendering workload passed on to the backend and also requires slightly less RAM. It can however introduce rendering artifacts at chunk boundaries depending on the backend, the antialiased flag and value of alpha.
linewidthsfloat or array-like, default: rcParams["contour.linewidth"] (default: None)

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).
linestyles{None, 'solid', 'dashed', 'dashdot', 'dotted'}, optional

Only applies to contour. If linestyles is None, the default is 'solid' unless the lines are monochrome. In that case, negative contours will 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.
hatcheslist[str], optional

Only applies to contourf. A list of cross hatch patterns to use on the filled areas. If None, no hatching will be added to the contour. Hatching is supported in the PostScript, PDF, SVG and Agg backends only.
dataindexable object, optional

If given, all parameters also accept a string s, which is interpreted as data[s] (unless this raises an exception).     Notes
contourf differs from the MATLAB version in that it does not draw the polygon edges. To draw edges, add line contours with calls to contour.
contourf fills intervals that are closed at the top; that is, for boundaries z1 and z2, the filled region is: z1 < Z <= z2
 except for the lowest interval, which is closed on both sides (i.e. it includes the lowest value).
contour and contourf use a marching squares algorithm to compute contour locations. More information can be found in the source src/_contour.h.


matplotlib.pyplot.cool   matplotlib.pyplot.cool()[source]

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.


matplotlib.pyplot.copper   matplotlib.pyplot.copper()[source]

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.


matplotlib.pyplot.csd   matplotlib.pyplot.csd(x, y, NFFT=None, Fs=None, Fc=None, detrend=None, window=None, noverlap=None, pad_to=None, sides=None, scale_by_freq=None, return_line=None, *, data=None, **kwargs)[source]

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.  Parameters

x, y1-D arrays or sequences

Arrays or sequences containing the data.
Fsfloat, default: 2

The sampling frequency (samples per time unit). It is used to calculate the Fourier frequencies, freqs, in cycles per time unit.
windowcallable or ndarray, default: window_hanning

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.
sides{'default', 'onesided', 'twosided'}, optional

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.
pad_toint, optional

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
NFFTint, default: 256

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.
detrend{'none', 'mean', 'linear'} or callable, default: 'none'

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.
scale_by_freqbool, default: True

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.
noverlapint, default: 0 (no overlap)

The number of points of overlap between segments.
Fcint, default: 0

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.
return_linebool, default: False

Whether to include the line object plotted in the returned values.    Returns

Pxy1-D array

The values for the cross spectrum \(P_{xy}\) before scaling (complex valued).
freqs1-D array

The frequencies corresponding to the elements in Pxy.
lineLine2D

The line created by this function. Only returned if return_line is True.    Other Parameters

dataindexable object, optional

If given, the following parameters also accept a string s, which is interpreted as data[s] (unless this raises an exception): x, y  **kwargs

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  psd

is equivalent to setting y = x.    Notes For plotting, the power is plotted as \(10 \log_{10}(P_{xy})\) for decibels, though \(P_{xy}\) itself is returned. References Bendat & Piersol -- Random Data: Analysis and Measurement Procedures, John Wiley & Sons (1986)


matplotlib.pyplot.delaxes   matplotlib.pyplot.delaxes(ax=None)[source]

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


matplotlib.pyplot.disconnect   matplotlib.pyplot.disconnect(cid)[source]

Disconnect the callback with id cid. Examples cid = canvas.mpl_connect('button_press_event', on_press)
# ... later
canvas.mpl_disconnect(cid)

  Examples using matplotlib.pyplot.disconnect

   Mouse move and click events


matplotlib.pyplot.draw   matplotlib.pyplot.draw()[source]

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.
  Examples using matplotlib.pyplot.draw

   Interactive functions

   Rotating a 3D plot

   Buttons

   Check Buttons

   Radio Buttons

   Textbox


matplotlib.pyplot.draw_if_interactive   matplotlib.pyplot.draw_if_interactive()[source]

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.


matplotlib.pyplot.errorbar   matplotlib.pyplot.errorbar(x, y, yerr=None, xerr=None, fmt='', ecolor=None, elinewidth=None, capsize=None, barsabove=False, lolims=False, uplims=False, xlolims=False, xuplims=False, errorevery=1, capthick=None, *, data=None, **kwargs)[source]

Plot y versus x as lines and/or markers with attached errorbars. x, y define the data locations, xerr, yerr define the errorbar sizes. By default, this draws the data markers/lines as well the errorbars. Use fmt='none' to draw errorbars without any data markers.  Parameters

x, yfloat or array-like

The data positions.
xerr, yerrfloat or array-like, shape(N,) or shape(2, N), optional

The errorbar sizes:  scalar: Symmetric +/- values for all data points. shape(N,): Symmetric +/-values for each data point. shape(2, N): Separate - and + values for each bar. First row contains the lower errors, the second row contains the upper errors.
None: No errorbar.  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.
fmtstr, default: ''

The format for the data points / data lines. See plot for details. Use 'none' (case insensitive) to plot errorbars without any data markers.
ecolorcolor, default: None

The color of the errorbar lines. If None, use the color of the line connecting the markers.
elinewidthfloat, default: None

The linewidth of the errorbar lines. If None, the linewidth of the current style is used.
capsizefloat, default: rcParams["errorbar.capsize"] (default: 0.0)

The length of the error bar caps in points.
capthickfloat, default: None

An alias to the keyword argument markeredgewidth (a.k.a. mew). This setting is a more sensible name for the property that controls the thickness of the error bar cap in points. For backwards compatibility, if mew or markeredgewidth are given, then they will over-ride capthick. This may change in future releases.
barsabovebool, default: False

If True, will plot the errorbars above the plot symbols. Default is below.
lolims, uplims, xlolims, xuplimsbool, default: False

These arguments can be used to indicate that a value gives only upper/lower limits. In that case a caret symbol is used to indicate this. lims-arguments may be scalars, or array-likes of the same length as xerr and yerr. To use limits with inverted axes, 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!
erroreveryint or (int, int), default: 1

draws error bars on a subset of the data. errorevery =N draws error bars on the points (x[::N], y[::N]). errorevery =(start, N) draws error bars on the points (x[start::N], y[start::N]). e.g. errorevery=(6, 3) adds error bars to the data at (x[6], x[9], x[12], x[15], ...). Used to avoid overlapping error bars when two series share x-axis values.    Returns
 ErrorbarContainer

The container contains:  plotline: Line2D instance of x, y plot markers and/or line. caplines: A tuple of Line2D instances of the error bar caps. barlinecols: A tuple of LineCollection with the horizontal and vertical error ranges.     Other Parameters

dataindexable object, optional

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  **kwargs

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: x, y, yerr = rand(3, 10)
errorbar(x, y, yerr, marker='s', mfc='red',
         mec='green', ms=20, mew=4)
 where mfc, mec, ms and mew are aliases for the longer property names, markerfacecolor, markeredgecolor, markersize and markeredgewidth. Valid kwargs for the marker properties are 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
  Examples using matplotlib.pyplot.errorbar

   Errorbar limit selection


matplotlib.pyplot.eventplot   matplotlib.pyplot.eventplot(positions, orientation='horizontal', lineoffsets=1, linelengths=1, linewidths=None, colors=None, linestyles='solid', *, data=None, **kwargs)[source]

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.  Parameters

positionsarray-like or list of array-like

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.
orientation{'horizontal', 'vertical'}, default: 'horizontal'

The direction of the event sequence:  'horizontal': the events are arranged horizontally. The indicator lines are vertical. 'vertical': the events are arranged vertically. The indicator lines are horizontal.
lineoffsetsfloat or array-like, default: 1

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.
linelengthsfloat or array-like, default: 1

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.
linewidthsfloat or array-like, default: rcParams["lines.linewidth"] (default: 1.5)

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.
colorscolor or list of colors, default: rcParams["lines.color"] (default: 'C0')

The color(s) of the event lines. If positions is 2D, this can be a sequence with length matching the length of positions.
linestylesstr or tuple or list of such values, default: 'solid'

Default is 'solid'. Valid strings are ['solid', 'dashed', 'dashdot', 'dotted', '-', '--', '-.', ':']. Dash tuples should be of the form: (offset, onoffseq),
 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.
dataindexable object, optional

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  **kwargs

Other keyword arguments are line collection properties. See LineCollection for a list of the valid properties.    Returns
 list of EventCollection

The EventCollection that were added.     Notes 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. Examples (Source code, png, pdf)


matplotlib.pyplot.figimage   matplotlib.pyplot.figimage(X, xo=0, yo=0, alpha=None, norm=None, cmap=None, vmin=None, vmax=None, origin=None, resize=False, **kwargs)[source]

Add a non-resampled image to the figure. The image is attached to the lower or upper left corner depending on origin.  Parameters
 X

The image data. This is an array of one of the following shapes:  MxN: luminance (grayscale) values MxNx3: RGB values MxNx4: RGBA values
xo, yoint

The x/y image offset in pixels.
alphaNone or float

The alpha blending value.
normmatplotlib.colors.Normalize

A Normalize instance to map the luminance to the interval [0, 1].
cmapstr or matplotlib.colors.Colormap, default: rcParams["image.cmap"] (default: 'viridis')

The colormap to use.
vmin, vmaxfloat

If norm is not given, these values set the data limits for the colormap.
origin{'upper', 'lower'}, default: rcParams["image.origin"] (default: 'upper')

Indicates where the [0, 0] index of the array is in the upper left or lower left corner of the axes.
resizebool

If True, resize the figure to match the given image size.    Returns
 matplotlib.image.FigureImage
  Other Parameters
 **kwargs

Additional kwargs are Artist kwargs passed on to FigureImage.     Notes 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]. Examples f = plt.figure()
nx = int(f.get_figwidth() * f.dpi)
ny = int(f.get_figheight() * f.dpi)
data = np.random.random((ny, nx))
f.figimage(data)
plt.show()


matplotlib.pyplot.figlegend   matplotlib.pyplot.figlegend(*args, **kwargs)[source]

Place a legend on the figure. Call signatures: figlegend()
figlegend(handles, labels)
figlegend(handles=handles)
figlegend(labels)
 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: ax.plot([1, 2, 3], label='Inline label')
fig.figlegend()
 or: line, = ax.plot([1, 2, 3])
line.set_label('Label via method')
fig.figlegend()
 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: fig.figlegend([line1, line2, line3], ['label1', 'label2', 'label3'])
 3. Explicitly listing the artists in the legend This is similar to 2, but the labels are taken from the artists' label properties. Example: line1, = ax1.plot([1, 2, 3], label='label1')
line2, = ax2.plot([1, 2, 3], label='label2')
fig.figlegend(handles=[line1, line2])
 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: fig, (ax1, ax2)  = plt.subplots(1, 2)
ax1.plot([1, 3, 5], color='blue')
ax2.plot([2, 4, 6], color='red')
fig.figlegend(['the blues', 'the reds'])
  Parameters

handleslist of Artist, optional

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.
labelslist of str, optional

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.    Returns
 Legend
  Other Parameters

locstr or pair of floats, default: rcParams["legend.loc"] (default: 'best') ('best' for axes, 'upper right' for figures)

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
bbox_to_anchorBboxBase, 2-tuple, or 4-tuple of floats

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): loc='best', bbox_to_anchor=(0.5, 0., 0.5, 0.5)
 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: loc='upper right', bbox_to_anchor=(0.5, 0.5)

ncolint, default: 1

The number of columns that the legend has.
propNone or matplotlib.font_manager.FontProperties or dict

The font properties of the legend. If None (default), the current matplotlib.rcParams will be used.
fontsizeint or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'}

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.
labelcolorstr or list, default: rcParams["legend.labelcolor"] (default: 'None')

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').
numpointsint, default: rcParams["legend.numpoints"] (default: 1)

The number of marker points in the legend when creating a legend entry for a Line2D (line).
scatterpointsint, default: rcParams["legend.scatterpoints"] (default: 1)

The number of marker points in the legend when creating a legend entry for a PathCollection (scatter plot).
scatteryoffsetsiterable of floats, default: [0.375, 0.5, 0.3125]

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].
markerscalefloat, default: rcParams["legend.markerscale"] (default: 1.0)

The relative size of legend markers compared with the originally drawn ones.
markerfirstbool, default: True

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.
frameonbool, default: rcParams["legend.frameon"] (default: True)

Whether the legend should be drawn on a patch (frame).
fancyboxbool, default: rcParams["legend.fancybox"] (default: True)

Whether round edges should be enabled around the FancyBboxPatch which makes up the legend's background.
shadowbool, default: rcParams["legend.shadow"] (default: False)

Whether to draw a shadow behind the legend.
framealphafloat, default: rcParams["legend.framealpha"] (default: 0.8)

The alpha transparency of the legend's background. If shadow is activated and framealpha is None, the default value is ignored.
facecolor"inherit" or color, default: rcParams["legend.facecolor"] (default: 'inherit')

The legend's background color. If "inherit", use rcParams["axes.facecolor"] (default: 'white').
edgecolor"inherit" or color, default: rcParams["legend.edgecolor"] (default: '0.8')

The legend's background patch edge color. If "inherit", use take rcParams["axes.edgecolor"] (default: 'black').
mode{"expand", None}

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).
bbox_transformNone or matplotlib.transforms.Transform

The transform for the bounding box (bbox_to_anchor). For a value of None (default) the Axes' transAxes transform will be used.
titlestr or None

The legend's title. Default is no title (None).
title_fontpropertiesNone or matplotlib.font_manager.FontProperties or dict

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.
title_fontsizeint or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'}, default: rcParams["legend.title_fontsize"] (default: None)

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.
borderpadfloat, default: rcParams["legend.borderpad"] (default: 0.4)

The fractional whitespace inside the legend border, in font-size units.
labelspacingfloat, default: rcParams["legend.labelspacing"] (default: 0.5)

The vertical space between the legend entries, in font-size units.
handlelengthfloat, default: rcParams["legend.handlelength"] (default: 2.0)

The length of the legend handles, in font-size units.
handleheightfloat, default: rcParams["legend.handleheight"] (default: 0.7)

The height of the legend handles, in font-size units.
handletextpadfloat, default: rcParams["legend.handletextpad"] (default: 0.8)

The pad between the legend handle and text, in font-size units.
borderaxespadfloat, default: rcParams["legend.borderaxespad"] (default: 0.5)

The pad between the axes and legend border, in font-size units.
columnspacingfloat, default: rcParams["legend.columnspacing"] (default: 2.0)

The spacing between columns, in font-size units.
handler_mapdict or None

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  Axes.legend
  Notes Some artists are not supported by this function. See Legend guide for details.


matplotlib.pyplot.fignum_exists   matplotlib.pyplot.fignum_exists(num)[source]

Return whether the figure with the given id exists.


matplotlib.pyplot.figtext   matplotlib.pyplot.figtext(x, y, s, fontdict=None, **kwargs)[source]

Add text to figure.  Parameters

x, yfloat

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.
sstr

The text string.
fontdictdict, optional

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.    Returns
 Text
  Other Parameters

**kwargsText properties

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  Axes.text
pyplot.text

  Examples using matplotlib.pyplot.figtext

   Fonts demo (object-oriented style)

   Fonts demo (keyword arguments)


matplotlib.pyplot.figure   matplotlib.pyplot.figure(num=None, figsize=None, dpi=None, facecolor=None, edgecolor=None, frameon=True, FigureClass=<class 'matplotlib.figure.Figure'>, clear=False, **kwargs)[source]

Create a new figure, or activate an existing figure.  Parameters

numint or str or Figure, optional

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.
figsize(float, float), default: rcParams["figure.figsize"] (default: [6.4, 4.8])

Width, height in inches.
dpifloat, default: rcParams["figure.dpi"] (default: 100.0)

The resolution of the figure in dots-per-inch.
facecolorcolor, default: rcParams["figure.facecolor"] (default: 'white')

The background color.
edgecolorcolor, default: rcParams["figure.edgecolor"] (default: 'white')

The border color.
frameonbool, default: True

If False, suppress drawing the figure frame.
FigureClasssubclass of Figure

Optionally use a custom Figure instance.
clearbool, default: False

If True and the figure already exists, then it is cleared.
tight_layoutbool or dict, default: rcParams["figure.autolayout"] (default: False)

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.
constrained_layoutbool, default: rcParams["figure.constrained_layout.use"] (default: False)

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.)  **kwargs : optional

See Figure for other possible arguments.    Returns
 Figure

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.     Notes 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.
  Examples using matplotlib.pyplot.figure

   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


matplotlib.pyplot.fill   matplotlib.pyplot.fill(*args, data=None, **kwargs)[source]

Plot filled polygons.  Parameters

*argssequence of x, y, [color]

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: ax.fill(x, y)                    # a polygon with default color
ax.fill(x, y, "b")               # a blue polygon
ax.fill(x, y, x2, y2)            # two polygons
ax.fill(x, y, "b", x2, y2, "r")  # a blue and a red polygon

dataindexable object, optional

An object with labelled data. If given, provide the label names to plot in x and y, e.g.: ax.fill("time", "signal",
        data={"time": [0, 1, 2], "signal": [0, 1, 0]})
    Returns
 list of Polygon

  Other Parameters

**kwargsPolygon properties

   Notes Use fill_between() if you would like to fill the region between two curves.
  Examples using matplotlib.pyplot.fill

   Filled polygon

   Interactive functions

   Fill Spiral


matplotlib.pyplot.fill_between   matplotlib.pyplot.fill_between(x, y1, y2=0, where=None, interpolate=False, step=None, *, data=None, **kwargs)[source]

Fill the area between two horizontal curves. The curves are defined by the points (x, y1) and (x, y2). This creates one or multiple polygons describing the filled area. You may exclude some horizontal sections from filling using where. By default, the edges connect the given points directly. Use step if the filling should be a step function, i.e. constant in between x.  Parameters

xarray (length N)

The x coordinates of the nodes defining the curves.
y1array (length N) or scalar

The y coordinates of the nodes defining the first curve.
y2array (length N) or scalar, default: 0

The y coordinates of the nodes defining the second curve.
wherearray of bool (length N), optional

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.
interpolatebool, default: False

This option is only relevant if where is used and the two curves are crossing each other. Semantically, where is often used for y1 > y2 or similar. By default, the nodes of the polygon defining the filled region will only be placed at the positions in the x array. Such a polygon cannot describe the above semantics close to the intersection. The x-sections containing the intersection are simply clipped. Setting interpolate to True will calculate the actual intersection point and extend the filled region up to this point.
step{'pre', 'post', 'mid'}, optional

Define step if the filling should be a step function, i.e. constant in between x. The value determines where the step will occur:  'pre': The y value is continued constantly to the left from every x position, i.e. the interval (x[i-1], x[i]] has the value y[i]. 'post': The y value is continued constantly to the right from every x position, i.e. the interval [x[i], x[i+1]) has the value y[i]. 'mid': Steps occur half-way between the x positions.     Returns
 PolyCollection

A PolyCollection containing the plotted polygons.    Other Parameters

dataindexable object, optional

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  **kwargs

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

Fill between two sets of y-values.  fill_betweenx

Fill between two sets of x-values.


matplotlib.pyplot.fill_betweenx   matplotlib.pyplot.fill_betweenx(y, x1, x2=0, where=None, step=None, interpolate=False, *, data=None, **kwargs)[source]

Fill the area between two vertical curves. The curves are defined by the points (y, x1) and (y, x2). This creates one or multiple polygons describing the filled area. You may exclude some vertical sections from filling using where. By default, the edges connect the given points directly. Use step if the filling should be a step function, i.e. constant in between y.  Parameters

yarray (length N)

The y coordinates of the nodes defining the curves.
x1array (length N) or scalar

The x coordinates of the nodes defining the first curve.
x2array (length N) or scalar, default: 0

The x coordinates of the nodes defining the second curve.
wherearray of bool (length N), optional

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.
interpolatebool, default: False

This option is only relevant if where is used and the two curves are crossing each other. Semantically, where is often used for x1 > x2 or similar. By default, the nodes of the polygon defining the filled region will only be placed at the positions in the y array. Such a polygon cannot describe the above semantics close to the intersection. The y-sections containing the intersection are simply clipped. Setting interpolate to True will calculate the actual intersection point and extend the filled region up to this point.
step{'pre', 'post', 'mid'}, optional

Define step if the filling should be a step function, i.e. constant in between y. The value determines where the step will occur:  'pre': The y value is continued constantly to the left from every x position, i.e. the interval (x[i-1], x[i]] has the value y[i]. 'post': The y value is continued constantly to the right from every x position, i.e. the interval [x[i], x[i+1]) has the value y[i]. 'mid': Steps occur half-way between the x positions.     Returns
 PolyCollection

A PolyCollection containing the plotted polygons.    Other Parameters

dataindexable object, optional

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  **kwargs

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

Fill between two sets of y-values.  fill_betweenx

Fill between two sets of x-values.


matplotlib.pyplot.findobj   matplotlib.pyplot.findobj(o=None, match=None, include_self=True)[source]

Find artist objects. Recursively find all Artist instances contained in the artist.  Parameters
 match

A filter criterion for the matches. This can be
None: Return all objects contained in artist. A function with signature def match(artist: Artist) -> bool. The result will only contain artists for which the function returns True. A class instance: e.g., Line2D. The result will only contain artists of this class or its subclasses (isinstance check).
include_selfbool

Include self in the list to be checked for a match.    Returns
 list of Artist


matplotlib.pyplot.flag   matplotlib.pyplot.flag()[source]

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.


matplotlib.pyplot.gca   matplotlib.pyplot.gca(**kwargs)[source]

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
  Examples using matplotlib.pyplot.gca

   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


matplotlib.pyplot.gcf   matplotlib.pyplot.gcf()[source]

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.)


matplotlib.pyplot.gci   matplotlib.pyplot.gci()[source]

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. Notes Historically, the only colorable artists were images; hence the name gci (get current image).


matplotlib.pyplot.get   matplotlib.pyplot.get(obj, *args, **kwargs)[source]

Return the value of an Artist's property, or print all of them.  Parameters

objArtist

The queried artist; e.g., a Line2D, a Text, or an Axes.
propertystr or None, default: None

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  setp


matplotlib.pyplot.get_current_fig_manager   matplotlib.pyplot.get_current_fig_manager()[source]

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.  Returns

FigureManagerBase or backend-dependent subclass thereof


matplotlib.pyplot.get_figlabels   matplotlib.pyplot.get_figlabels()[source]

Return a list of existing figure labels.


matplotlib.pyplot.get_fignums   matplotlib.pyplot.get_fignums()[source]

Return a list of existing figure numbers.


matplotlib.pyplot.get_plot_commands   matplotlib.pyplot.get_plot_commands()[source]

Get a sorted list of all of the plotting commands.


matplotlib.pyplot.getp   matplotlib.pyplot.getp(obj, *args, **kwargs)[source]

Return the value of an Artist's property, or print all of them.  Parameters

objArtist

The queried artist; e.g., a Line2D, a Text, or an Axes.
propertystr or None, default: None

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  setp

  Examples using matplotlib.pyplot.getp

   Set and get properties

   Artist tutorial


matplotlib.pyplot.ginput   matplotlib.pyplot.ginput(n=1, timeout=30, show_clicks=True, mouse_add=MouseButton.LEFT, mouse_pop=MouseButton.RIGHT, mouse_stop=MouseButton.MIDDLE)[source]

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:  Add a point. Remove the most recently added point. Stop the interaction and return the points added so far.  The actions are assigned to mouse buttons via the arguments mouse_add, mouse_pop and mouse_stop.  Parameters

nint, default: 1

Number of mouse clicks to accumulate. If negative, accumulate clicks until the input is terminated manually.
timeoutfloat, default: 30 seconds

Number of seconds to wait before timing out. If zero or negative will never timeout.
show_clicksbool, default: True

If True, show a red cross at the location of each click.
mouse_addMouseButton or None, default: MouseButton.LEFT

Mouse button used to add points.
mouse_popMouseButton or None, default: MouseButton.RIGHT

Mouse button used to remove the most recently added point.
mouse_stopMouseButton or None, default: MouseButton.MIDDLE

Mouse button used to stop input.    Returns
 list of tuples

A list of the clicked (x, y) coordinates.     Notes 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.
  Examples using matplotlib.pyplot.ginput

   Interactive functions


matplotlib.pyplot.gray   matplotlib.pyplot.gray()[source]

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.


matplotlib.pyplot.grid   matplotlib.pyplot.grid(visible=None, which='major', axis='both', **kwargs)[source]

Configure the grid lines.  Parameters

visiblebool or None, optional

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.
which{'major', 'minor', 'both'}, optional

The grid lines to apply the changes on.
axis{'both', 'x', 'y'}, optional

The axis to apply the changes on.
**kwargsLine2D properties

Define the line properties of the grid, e.g.: grid(color='r', linestyle='-', linewidth=2)
 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       Notes 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.
  Examples using matplotlib.pyplot.grid

   Step Demo

   Geographic Projections

   Pyplot Text

   Customize Rc

   Findobj Demo

   Custom scale

   SkewT-logP diagram: using transforms and custom projections

   Pyplot tutorial


matplotlib.pyplot.hexbin   matplotlib.pyplot.hexbin(x, y, C=None, gridsize=100, bins=None, xscale='linear', yscale='linear', extent=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, edgecolors='face', reduce_C_function=<function mean>, mincnt=None, marginals=False, *, data=None, **kwargs)[source]

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.  Parameters

x, yarray-like

The data positions. x and y must be of the same length.
Carray-like, optional

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.
gridsizeint or (int, int), default: 100

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.
bins'log' or int or sequence, default: None

Discretization of the hexagon values.  If None, no binning is applied; the color of each hexagon directly corresponds to its count value. If 'log', use a logarithmic scale for the colormap. Internally, \(log_{10}(i+1)\) is used to determine the hexagon color. This is equivalent to norm=LogNorm(). If an integer, divide the counts in the specified number of bins, and color the hexagons accordingly. If a sequence of values, the values of the lower bound of the bins to be used.
xscale{'linear', 'log'}, default: 'linear'

Use a linear or log10 scale on the horizontal axis.
yscale{'linear', 'log'}, default: 'linear'

Use a linear or log10 scale on the vertical axis.
mincntint > 0, default: None

If not None, only display cells with more than mincnt number of points in the cell.
marginalsbool, default: False

If marginals is True, plot the marginal density as colormapped rectangles along the bottom of the x-axis and left of the y-axis.
extent4-tuple of float, default: None

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).    Returns
 PolyCollection

A PolyCollection defining the hexagonal bins.
PolyCollection.get_offsets contains a Mx2 array containing the x, y positions of the M hexagon centers.
PolyCollection.get_array contains the values of the M hexagons.  If marginals is True, horizontal bar and vertical bar (both PolyCollections) will be attached to the return collection as attributes hbar and vbar.    Other Parameters

cmapstr or Colormap, default: rcParams["image.cmap"] (default: 'viridis')

The Colormap instance or registered colormap name used to map the bin values to colors.
normNormalize, optional

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.
vmin, vmaxfloat, default: None

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.
alphafloat between 0 and 1, optional

The alpha blending value, between 0 (transparent) and 1 (opaque).
linewidthsfloat, default: None

If None, defaults to 1.0.
edgecolors{'face', 'none', None} or color, default: 'face'

The color of the hexagon edges. Possible values are:  'face': Draw the edges in the same color as the fill color. 'none': No edges are drawn. This can sometimes lead to unsightly unpainted pixels between the hexagons.
None: Draw outlines in the default color. An explicit color.
reduce_C_functioncallable, default: numpy.mean

The function to aggregate C within the bins. It is ignored if C is not given. This must have the signature: def reduce_C_function(C: array) -> float
 Commonly used functions are:
numpy.mean: average of the points
numpy.sum: integral of the point values
numpy.amax: value taken from the largest point
dataindexable object, optional

If given, the following parameters also accept a string s, which is interpreted as data[s] (unless this raises an exception): x, y, C
**kwargsPolyCollection properties

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  hist2d

2D histogram rectangular bins


matplotlib.pyplot.hist   matplotlib.pyplot.hist(x, bins=None, range=None, density=False, weights=None, cumulative=False, bottom=None, histtype='bar', align='mid', orientation='vertical', rwidth=None, log=False, color=None, label=None, stacked=False, *, data=None, **kwargs)[source]

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.  Parameters

x(n,) array or sequence of (n,) arrays

Input values, this takes either a single array or a sequence of arrays which are not required to be of the same length.
binsint or sequence or str, default: rcParams["hist.bins"] (default: 10)

If bins is an integer, it defines the number of equal-width bins in the range. If bins is a sequence, it defines the bin edges, including the left edge of the first bin and the right edge of the last bin; in this case, bins may be unequally spaced. All but the last (righthand-most) bin is half-open. In other words, if bins is: [1, 2, 3, 4]
 then the first bin is [1, 2) (including 1, but excluding 2) and the second [2, 3). The last bin, however, is [3, 4], which includes 4. If bins is a string, it is one of the binning strategies supported by numpy.histogram_bin_edges: 'auto', 'fd', 'doane', 'scott', 'stone', 'rice', 'sturges', or 'sqrt'.
rangetuple or None, default: None

The lower and upper range of the bins. Lower and upper outliers are ignored. If not provided, range is (x.min(), x.max()). Range has no effect if bins is a sequence. If bins is a sequence or range is specified, autoscaling is based on the specified bin range instead of the range of x.
densitybool, default: False

If True, draw and return a probability density: each bin will display the bin's raw count divided by the total number of counts and the bin width (density = counts / (sum(counts) * np.diff(bins))), so that the area under the histogram integrates to 1 (np.sum(density * np.diff(bins)) == 1). If stacked is also True, the sum of the histograms is normalized to 1.
weights(n,) array-like or None, default: None

An array of weights, of the same shape as x. Each value in x only contributes its associated weight towards the bin count (instead of 1). If density is True, the weights are normalized, so that the integral of the density over the range remains 1. 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) counts, bins = np.histogram(data)
plt.hist(bins[:-1], bins, weights=counts)
 (or you may alternatively use bar()).
cumulativebool or -1, default: False

If True, then a histogram is computed where each bin gives the counts in that bin plus all bins for smaller values. The last bin gives the total number of datapoints. If density is also 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.
bottomarray-like, scalar, or None, default: None

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.
histtype{'bar', 'barstacked', 'step', 'stepfilled'}, default: 'bar'

The type of histogram to draw.  'bar' is a traditional bar-type histogram. If multiple data are given the bars are arranged side by side. 'barstacked' is a bar-type histogram where multiple data are stacked on top of each other. 'step' generates a lineplot that is by default unfilled. 'stepfilled' generates a lineplot that is by default filled.
align{'left', 'mid', 'right'}, default: 'mid'

The horizontal alignment of the histogram bars.  'left': bars are centered on the left bin edges. 'mid': bars are centered between the bin edges. 'right': bars are centered on the right bin edges.
orientation{'vertical', 'horizontal'}, default: 'vertical'

If 'horizontal', barh will be used for bar-type histograms and the bottom kwarg will be the left edges.
rwidthfloat or None, default: None

The relative width of the bars as a fraction of the bin width. If None, automatically compute the width. Ignored if histtype is 'step' or 'stepfilled'.
logbool, default: False

If True, the histogram axis will be set to a log scale.
colorcolor or array-like of colors or None, default: None

Color or sequence of colors, one per dataset. Default (None) uses the standard line color sequence.
labelstr or None, default: None

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.
stackedbool, default: False

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'    Returns

narray or list of arrays

The values of the histogram bins. See density and weights for a description of the possible semantics. If input x is an array, then this is an array of length nbins. If input is a sequence of arrays [data1, data2, ...], then this is a list of arrays with the values of the histograms for each of the arrays in the same order. The dtype of the array n (or of its element arrays) will always be float even if no weighting or normalization is used.
binsarray

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.
patchesBarContainer or list of a single Polygon or list of such objects

Container of individual artists used to create the histogram or list of such containers if there are multiple input datasets.    Other Parameters

dataindexable object, optional

If given, the following parameters also accept a string s, which is interpreted as data[s] (unless this raises an exception): x, weights  **kwargs

Patch properties      See also  hist2d

2D histogram with rectangular bins  hexbin

2D histogram with hexagonal bins    Notes For large numbers of bins (>1000), 'step' and 'stepfilled' can be significantly faster than 'bar' and 'barstacked'.
  Examples using matplotlib.pyplot.hist

   Pyplot Text

   Animated histogram

   SVG Histogram

   Pyplot tutorial

   Image tutorial


matplotlib.pyplot.hist2d   matplotlib.pyplot.hist2d(x, y, bins=10, range=None, density=False, weights=None, cmin=None, cmax=None, *, data=None, **kwargs)[source]

Make a 2D histogram plot.  Parameters

x, yarray-like, shape (n, )

Input values
binsNone or int or [int, int] or array-like or [array, array]

The bin specification:  If int, the number of bins for the two dimensions (nx=ny=bins). If [int, int], the number of bins in each dimension (nx, ny = bins). If array-like, the bin edges for the two dimensions (x_edges=y_edges=bins). If [array, array], the bin edges in each dimension (x_edges, y_edges = bins).  The default value is 10.
rangearray-like shape(2, 2), optional

The leftmost and rightmost edges of the bins along each dimension (if not specified explicitly in the bins parameters): [[xmin,
xmax], [ymin, ymax]]. All values outside of this range will be considered outliers and not tallied in the histogram.
densitybool, default: False

Normalize histogram. See the documentation for the density parameter of hist for more details.
weightsarray-like, shape (n, ), optional

An array of values w_i weighing each sample (x_i, y_i).
cmin, cmaxfloat, default: None

All bins that has count less than cmin or more than cmax will not be displayed (set to NaN before passing to imshow) and these count values in the return value count histogram will also be set to nan upon return.    Returns

h2D array

The bi-dimensional histogram of samples x and y. Values in x are histogrammed along the first dimension and values in y are histogrammed along the second dimension.
xedges1D array

The bin edges along the x axis.
yedges1D array

The bin edges along the y axis.
imageQuadMesh

  Other Parameters

cmapColormap or str, optional

A colors.Colormap instance. If not set, use rc settings.
normNormalize, optional

A colors.Normalize instance is used to scale luminance data to [0, 1]. If not set, defaults to colors.Normalize().
vmin/vmaxNone or scalar, optional

Arguments passed to the Normalize instance.
alpha0 <= scalar <= 1 or None, optional

The alpha blending value.
dataindexable object, optional

If given, the following parameters also accept a string s, which is interpreted as data[s] (unless this raises an exception): x, y, weights  **kwargs

Additional parameters are passed along to the pcolormesh method and QuadMesh constructor.      See also  hist

1D histogram plotting  hexbin

2D histogram with hexagonal bins    Notes  Currently hist2d calculates its own axis limits, and any limits previously set are ignored. Rendering the histogram with a logarithmic color scale is accomplished by passing a colors.LogNorm instance to the norm keyword argument. Likewise, power-law normalization (similar in effect to gamma correction) can be accomplished with colors.PowerNorm.


matplotlib.pyplot.hlines   matplotlib.pyplot.hlines(y, xmin, xmax, colors=None, linestyles='solid', label='', *, data=None, **kwargs)[source]

Plot horizontal lines at each y from xmin to xmax.  Parameters

yfloat or array-like

y-indexes where to plot the lines.
xmin, xmaxfloat or array-like

Respective beginning and end of each line. If scalars are provided, all lines will have same length.
colorslist of colors, default: rcParams["lines.color"] (default: 'C0')

linestyles{'solid', 'dashed', 'dashdot', 'dotted'}, optional

labelstr, default: ''

  Returns
 LineCollection
  Other Parameters

dataindexable object, optional

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
**kwargsLineCollection properties.

    See also  vlines

vertical lines  axhline

horizontal line across the Axes


matplotlib.pyplot.hot   matplotlib.pyplot.hot()[source]

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.


matplotlib.pyplot.hsv   matplotlib.pyplot.hsv()[source]

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.


matplotlib.pyplot.imread   matplotlib.pyplot.imread(fname, format=None)[source]

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.   Parameters

fnamestr or file-like

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))).
formatstr, optional

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.    Returns
 numpy.array

The image data. The returned array has shape  (M, N) for grayscale images. (M, N, 3) for RGB images. (M, N, 4) for RGBA images.  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.
  Examples using matplotlib.pyplot.imread

   Clipping images with patches

   Image Demo

   AnnotationBbox demo

   Using a text as a Path

   Convert texts to images

   Ribbon Box