doc_content
stringlengths 1
386k
| doc_id
stringlengths 5
188
|
---|---|
matplotlib.pyplot.get_fignums matplotlib.pyplot.get_fignums()[source]
Return a list of existing figure numbers.
|
matplotlib._as_gen.matplotlib.pyplot.get_fignums
|
matplotlib.pyplot.get_plot_commands matplotlib.pyplot.get_plot_commands()[source]
Get a sorted list of all of the plotting commands.
|
matplotlib._as_gen.matplotlib.pyplot.get_plot_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._as_gen.matplotlib.pyplot.getp
|
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._as_gen.matplotlib.pyplot.ginput
|
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._as_gen.matplotlib.pyplot.gray
|
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._as_gen.matplotlib.pyplot.grid
|
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._as_gen.matplotlib.pyplot.hexbin
|
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._as_gen.matplotlib.pyplot.hist
|
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._as_gen.matplotlib.pyplot.hist2d
|
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._as_gen.matplotlib.pyplot.hlines
|
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._as_gen.matplotlib.pyplot.hot
|
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._as_gen.matplotlib.pyplot.hsv
|
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
|
matplotlib._as_gen.matplotlib.pyplot.imread
|
matplotlib.pyplot.imsave matplotlib.pyplot.imsave(fname, arr, **kwargs)[source]
Save an array as an image file. Parameters
fnamestr or path-like or file-like
A path or a file-like object to store the image in. If format is not set, then the output format is inferred from the extension of fname, if any, and from rcParams["savefig.format"] (default: 'png') otherwise. If format is set, it determines the output format.
arrarray-like
The image data. The shape can be one of MxN (luminance), MxNx3 (RGB) or MxNx4 (RGBA).
vmin, vmaxfloat, optional
vmin and vmax set the color scaling for the image by fixing the values that map to the colormap color limits. If either vmin or vmax is None, that limit is determined from the arr min/max value.
cmapstr or Colormap, default: rcParams["image.cmap"] (default: 'viridis')
A Colormap instance or registered colormap name. The colormap maps scalar data to colors. It is ignored for RGB(A) data.
formatstr, optional
The file format, e.g. 'png', 'pdf', 'svg', ... The behavior when this is unset is documented under fname.
origin{'upper', 'lower'}, default: rcParams["image.origin"] (default: 'upper')
Indicates whether the (0, 0) index of the array is in the upper left or lower left corner of the axes.
dpifloat
The DPI to store in the metadata of the file. This does not affect the resolution of the output image. Depending on file format, this may be rounded to the nearest integer.
metadatadict, optional
Metadata in the image file. The supported keys depend on the output format, see the documentation of the respective backends for more information.
pil_kwargsdict, optional
Keyword arguments passed to PIL.Image.Image.save. If the 'pnginfo' key is present, it completely overrides metadata, including the default 'Software' key.
|
matplotlib._as_gen.matplotlib.pyplot.imsave
|
matplotlib.pyplot.imshow matplotlib.pyplot.imshow(X, cmap=None, norm=None, *, aspect=None, interpolation=None, alpha=None, vmin=None, vmax=None, origin=None, extent=None, interpolation_stage=None, filternorm=True, filterrad=4.0, resample=None, url=None, data=None, **kwargs)[source]
Display data as an image, i.e., on a 2D regular raster. The input may either be actual RGB(A) data, or 2D scalar data, which will be rendered as a pseudocolor image. For displaying a grayscale image set up the colormapping using the parameters cmap='gray', vmin=0, vmax=255. The number of pixels used to render an image is set by the Axes size and the dpi of the figure. This can lead to aliasing artifacts when the image is resampled because the displayed image size will usually not match the size of X (see Image antialiasing). The resampling can be controlled via the interpolation parameter and/or rcParams["image.interpolation"] (default: 'antialiased'). Parameters
Xarray-like or PIL image
The image data. Supported array shapes are: (M, N): an image with scalar data. The values are mapped to colors using normalization and a colormap. See parameters norm, cmap, vmin, vmax. (M, N, 3): an image with RGB values (0-1 float or 0-255 int). (M, N, 4): an image with RGBA values (0-1 float or 0-255 int), i.e. including transparency. The first two dimensions (M, N) define the rows and columns of the image. Out-of-range RGB(A) values are clipped.
cmapstr or Colormap, default: rcParams["image.cmap"] (default: 'viridis')
The Colormap instance or registered colormap name used to map scalar data to colors. This parameter is ignored for RGB(A) data.
normNormalize, optional
The Normalize instance used to scale scalar data to the [0, 1] range before mapping to colors using cmap. By default, a linear scaling mapping the lowest value to 0 and the highest to 1 is used. This parameter is ignored for RGB(A) data.
aspect{'equal', 'auto'} or float, default: rcParams["image.aspect"] (default: 'equal')
The aspect ratio of the Axes. This parameter is particularly relevant for images since it determines whether data pixels are square. This parameter is a shortcut for explicitly calling Axes.set_aspect. See there for further details. 'equal': Ensures an aspect ratio of 1. Pixels will be square (unless pixel sizes are explicitly made non-square in data coordinates using extent). 'auto': The Axes is kept fixed and the aspect is adjusted so that the data fit in the Axes. In general, this will result in non-square pixels.
interpolationstr, default: rcParams["image.interpolation"] (default: 'antialiased')
The interpolation method used. Supported values are 'none', 'antialiased', 'nearest', 'bilinear', 'bicubic', 'spline16', 'spline36', 'hanning', 'hamming', 'hermite', 'kaiser', 'quadric', 'catrom', 'gaussian', 'bessel', 'mitchell', 'sinc', 'lanczos', 'blackman'. If interpolation is 'none', then no interpolation is performed on the Agg, ps, pdf and svg backends. Other backends will fall back to 'nearest'. Note that most SVG renderers perform interpolation at rendering and that the default interpolation method they implement may differ. If interpolation is the default 'antialiased', then 'nearest' interpolation is used if the image is upsampled by more than a factor of three (i.e. the number of display pixels is at least three times the size of the data array). If the upsampling rate is smaller than 3, or the image is downsampled, then 'hanning' interpolation is used to act as an anti-aliasing filter, unless the image happens to be upsampled by exactly a factor of two or one. See Interpolations for imshow for an overview of the supported interpolation methods, and Image antialiasing for a discussion of image antialiasing. Some interpolation methods require an additional radius parameter, which can be set by filterrad. Additionally, the antigrain image resize filter is controlled by the parameter filternorm.
interpolation_stage{'data', 'rgba'}, default: 'data'
If 'data', interpolation is carried out on the data provided by the user. If 'rgba', the interpolation is carried out after the colormapping has been applied (visual interpolation).
alphafloat or array-like, optional
The alpha blending value, between 0 (transparent) and 1 (opaque). If alpha is an array, the alpha blending values are applied pixel by pixel, and alpha must have the same shape as X.
vmin, vmaxfloat, optional
When using scalar data and no explicit norm, vmin and vmax define the data range that the colormap covers. By default, the colormap covers the complete value range of the supplied data. It is an error to use vmin/vmax when norm is given. When using RGB(A) data, parameters vmin/vmax are ignored.
origin{'upper', 'lower'}, default: rcParams["image.origin"] (default: 'upper')
Place the [0, 0] index of the array in the upper left or lower left corner of the Axes. The convention (the default) 'upper' is typically used for matrices and images. Note that the vertical axis points upward for 'lower' but downward for 'upper'. See the origin and extent in imshow tutorial for examples and a more detailed description.
extentfloats (left, right, bottom, top), optional
The bounding box in data coordinates that the image will fill. The image is stretched individually along x and y to fill the box. The default extent is determined by the following conditions. Pixels have unit size in data coordinates. Their centers are on integer coordinates, and their center coordinates range from 0 to columns-1 horizontally and from 0 to rows-1 vertically. Note that the direction of the vertical axis and thus the default values for top and bottom depend on origin: For origin == 'upper' the default is (-0.5, numcols-0.5, numrows-0.5, -0.5). For origin == 'lower' the default is (-0.5, numcols-0.5, -0.5, numrows-0.5). See the origin and extent in imshow tutorial for examples and a more detailed description.
filternormbool, default: True
A parameter for the antigrain image resize filter (see the antigrain documentation). If filternorm is set, the filter normalizes integer values and corrects the rounding errors. It doesn't do anything with the source floating point values, it corrects only integers according to the rule of 1.0 which means that any sum of pixel weights must be equal to 1.0. So, the filter function must produce a graph of the proper shape.
filterradfloat > 0, default: 4.0
The filter radius for filters that have a radius parameter, i.e. when interpolation is one of: 'sinc', 'lanczos' or 'blackman'.
resamplebool, default: rcParams["image.resample"] (default: True)
When True, use a full resampling method. When False, only resample when the output image is larger than the input image.
urlstr, optional
Set the url of the created AxesImage. See Artist.set_url. Returns
AxesImage
Other Parameters
dataindexable object, optional
If given, all parameters also accept a string s, which is interpreted as data[s] (unless this raises an exception).
**kwargsArtist properties
These parameters are passed on to the constructor of the AxesImage artist. See also matshow
Plot a matrix or an array as an image. Notes Unless extent is used, pixel centers will be located at integer coordinates. In other words: the origin will coincide with the center of pixel (0, 0). There are two common representations for RGB images with an alpha channel: Straight (unassociated) alpha: R, G, and B channels represent the color of the pixel, disregarding its opacity. Premultiplied (associated) alpha: R, G, and B channels represent the color of the pixel, adjusted for its opacity by multiplication. imshow expects RGB images adopting the straight (unassociated) alpha representation.
Examples using matplotlib.pyplot.imshow
Layer Images
Subplots spacings and margins
Dolphins
Hyperlinks
Image tutorial
Tight Layout guide
|
matplotlib._as_gen.matplotlib.pyplot.imshow
|
matplotlib.pyplot.inferno matplotlib.pyplot.inferno()[source]
Set the colormap to 'inferno'. This changes the default colormap as well as the colormap of the current image if there is one. See help(colormaps) for more information.
|
matplotlib._as_gen.matplotlib.pyplot.inferno
|
matplotlib.pyplot.install_repl_displayhook matplotlib.pyplot.install_repl_displayhook()[source]
Install a repl display hook so that any stale figure are automatically redrawn when control is returned to the repl. This works both with IPython and with vanilla python shells.
|
matplotlib._as_gen.matplotlib.pyplot.install_repl_displayhook
|
matplotlib.pyplot.ioff matplotlib.pyplot.ioff()[source]
Disable interactive mode. See pyplot.isinteractive for more details. See also ion
Enable interactive mode. isinteractive
Whether interactive mode is enabled. show
Show all figures (and maybe block). pause
Show all figures, and block for a time. Notes For a temporary change, this can be used as a context manager: # if interactive mode is on
# then figures will be shown on creation
plt.ion()
# This figure will be shown immediately
fig = plt.figure()
with plt.ioff():
# interactive mode will be off
# figures will not automatically be shown
fig2 = plt.figure()
# ...
To enable usage as a context manager, this function returns an _IoffContext object. The return value is not intended to be stored or accessed by the user.
|
matplotlib._as_gen.matplotlib.pyplot.ioff
|
matplotlib.pyplot.ion matplotlib.pyplot.ion()[source]
Enable interactive mode. See pyplot.isinteractive for more details. See also ioff
Disable interactive mode. isinteractive
Whether interactive mode is enabled. show
Show all figures (and maybe block). pause
Show all figures, and block for a time. Notes For a temporary change, this can be used as a context manager: # if interactive mode is off
# then figures will not be shown on creation
plt.ioff()
# This figure will not be shown immediately
fig = plt.figure()
with plt.ion():
# interactive mode will be on
# figures will automatically be shown
fig2 = plt.figure()
# ...
To enable usage as a context manager, this function returns an _IonContext object. The return value is not intended to be stored or accessed by the user.
|
matplotlib._as_gen.matplotlib.pyplot.ion
|
matplotlib.pyplot.isinteractive matplotlib.pyplot.isinteractive()[source]
Return whether plots are updated after every plotting command. The interactive mode is mainly useful if you build plots from the command line and want to see the effect of each command while you are building the figure. In interactive mode: newly created figures will be shown immediately; figures will automatically redraw on change;
pyplot.show will not block by default. In non-interactive mode: newly created figures and changes to figures will not be reflected until explicitly asked to be;
pyplot.show will block by default. See also ion
Enable interactive mode. ioff
Disable interactive mode. show
Show all figures (and maybe block). pause
Show all figures, and block for a time.
|
matplotlib._as_gen.matplotlib.pyplot.isinteractive
|
matplotlib.pyplot.jet matplotlib.pyplot.jet()[source]
Set the colormap to 'jet'. This changes the default colormap as well as the colormap of the current image if there is one. See help(colormaps) for more information.
|
matplotlib._as_gen.matplotlib.pyplot.jet
|
matplotlib.pyplot.legend matplotlib.pyplot.legend(*args, **kwargs)[source]
Place a legend on the Axes. Call signatures: legend()
legend(handles, labels)
legend(handles=handles)
legend(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')
ax.legend()
or: line, = ax.plot([1, 2, 3])
line.set_label('Label via method')
ax.legend()
Specific lines can be excluded from the automatic legend element selection by defining a label starting with an underscore. This is default for all artists, so calling Axes.legend without any arguments and without setting the labels manually will result in no legend being drawn. 2. Explicitly listing the artists and labels in the legend For full control of which artists have a legend entry, it is possible to pass an iterable of legend artists followed by an iterable of legend labels respectively: ax.legend([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, = ax.plot([1, 2, 3], label='label1')
line2, = ax.plot([1, 2, 3], label='label2')
ax.legend(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 an Axes, call this function with an iterable of strings, one for each legend item. For example: ax.plot([1, 2, 3])
ax.plot([5, 6, 7])
ax.legend(['First line', 'Second line'])
Parameters
handlessequence 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 Figure.legend
Notes Some artists are not supported by this function. See Legend guide for details. Examples (Source code, png, pdf)
Examples using matplotlib.pyplot.legend
Errorbar limit selection
Plotting masked and NaN values
Scatter Symbol
Stairs Demo
Step Demo
Infinite lines
Parasite Simple
Findobj Demo
Zorder Demo
The Sankey class
SVG Histogram
Basic Usage
Legend guide
|
matplotlib._as_gen.matplotlib.pyplot.legend
|
matplotlib.pyplot.locator_params matplotlib.pyplot.locator_params(axis='both', tight=None, **kwargs)[source]
Control behavior of major tick locators. Because the locator is involved in autoscaling, autoscale_view is called automatically after the parameters are changed. Parameters
axis{'both', 'x', 'y'}, default: 'both'
The axis on which to operate.
tightbool or None, optional
Parameter passed to autoscale_view. Default is None, for no change. Other Parameters
**kwargs
Remaining keyword arguments are passed to directly to the set_params() method of the locator. Supported keywords depend on the type of the locator. See for example set_params for the ticker.MaxNLocator used by default for linear axes. Examples When plotting small subplots, one might want to reduce the maximum number of ticks and use tight bounds, for example: ax.locator_params(tight=True, nbins=4)
|
matplotlib._as_gen.matplotlib.pyplot.locator_params
|
matplotlib.pyplot.loglog matplotlib.pyplot.loglog(*args, **kwargs)[source]
Make a plot with log scaling on both the x and y axis. Call signatures: loglog([x], y, [fmt], data=None, **kwargs)
loglog([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)
This is just a thin wrapper around plot which additionally changes both the x-axis and the y-axis to log scaling. All of the concepts and parameters of plot can be used here as well. The additional parameters base, subs and nonpositive control the x/y-axis properties. They are just forwarded to Axes.set_xscale and Axes.set_yscale. To use different properties on the x-axis and the y-axis, use e.g. ax.set_xscale("log", base=10); ax.set_yscale("log", base=2). Parameters
basefloat, default: 10
Base of the logarithm.
subssequence, optional
The location of the minor ticks. If None, reasonable locations are automatically chosen depending on the number of decades in the plot. See Axes.set_xscale/Axes.set_yscale for details.
nonpositive{'mask', 'clip'}, default: 'mask'
Non-positive values can be masked as invalid, or clipped to a very small positive number. **kwargs
All parameters supported by plot. Returns
list of Line2D
Objects representing the plotted data.
|
matplotlib._as_gen.matplotlib.pyplot.loglog
|
matplotlib.pyplot.magma matplotlib.pyplot.magma()[source]
Set the colormap to 'magma'. This changes the default colormap as well as the colormap of the current image if there is one. See help(colormaps) for more information.
|
matplotlib._as_gen.matplotlib.pyplot.magma
|
matplotlib.pyplot.magnitude_spectrum matplotlib.pyplot.magnitude_spectrum(x, Fs=None, Fc=None, window=None, pad_to=None, sides=None, scale=None, *, data=None, **kwargs)[source]
Plot the magnitude spectrum. Compute the magnitude spectrum of x. Data is padded to a length of pad_to and the windowing function window is applied to the signal. Parameters
x1-D array or sequence
Array or sequence 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. While not increasing the actual resolution of the spectrum (the minimum distance between resolvable peaks), this can give more points in the plot, allowing for more detail. This corresponds to the n parameter in the call to fft(). The default is None, which sets pad_to equal to the length of the input signal (i.e. no padding).
scale{'default', 'linear', 'dB'}
The scaling of the values in the spec. 'linear' is no scaling. 'dB' returns the values in dB scale, i.e., the dB amplitude (20 * log10). 'default' is 'linear'.
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. Returns
spectrum1-D array
The values for the magnitude spectrum before scaling (real valued).
freqs1-D array
The frequencies corresponding to the elements in spectrum.
lineLine2D
The line created by this function. 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 **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
Plots the power spectral density. angle_spectrum
Plots the angles of the corresponding frequencies. phase_spectrum
Plots the phase (unwrapped angle) of the corresponding frequencies. specgram
Can plot the magnitude spectrum of segments within the signal in a colormap.
|
matplotlib._as_gen.matplotlib.pyplot.magnitude_spectrum
|
matplotlib.pyplot.margins matplotlib.pyplot.margins(*margins, x=None, y=None, tight=True)[source]
Set or retrieve autoscaling margins. The padding added to each limit of the Axes is the margin times the data interval. All input parameters must be floats within the range [0, 1]. Passing both positional and keyword arguments is invalid and will raise a TypeError. If no arguments (positional or otherwise) are provided, the current margins will remain in place and simply be returned. Specifying any margin changes only the autoscaling; for example, if xmargin is not None, then xmargin times the X data interval will be added to each end of that interval before it is used in autoscaling. Parameters
*marginsfloat, optional
If a single positional argument is provided, it specifies both margins of the x-axis and y-axis limits. If two positional arguments are provided, they will be interpreted as xmargin, ymargin. If setting the margin on a single axis is desired, use the keyword arguments described below.
x, yfloat, optional
Specific margin values for the x-axis and y-axis, respectively. These cannot be used with positional arguments, but can be used individually to alter on e.g., only the y-axis.
tightbool or None, default: True
The tight parameter is passed to autoscale_view(), which is executed after a margin is changed; the default here is True, on the assumption that when margins are specified, no additional padding to match tick marks is usually desired. Set tight to None will preserve the previous setting. Returns
xmargin, ymarginfloat
Notes If a previously used Axes method such as pcolor() has set use_sticky_edges to True, only the limits not set by the "sticky artists" will be modified. To force all of the margins to be set, set use_sticky_edges to False before calling margins().
Examples using matplotlib.pyplot.margins
Rotating custom tick labels
|
matplotlib._as_gen.matplotlib.pyplot.margins
|
matplotlib.pyplot.matshow matplotlib.pyplot.matshow(A, fignum=None, **kwargs)[source]
Display an array as a matrix in a new figure window. The origin is set at the upper left hand corner and rows (first dimension of the array) are displayed horizontally. The aspect ratio of the figure window is that of the array, unless this would make an excessively short or narrow figure. Tick labels for the xaxis are placed on top. Parameters
A2D array-like
The matrix to be displayed.
fignumNone or int or False
If None, create a new figure window with automatic numbering. If a nonzero integer, draw into the figure with the given number (create it if it does not exist). If 0, use the current axes (or create one if it does not exist). Note Because of how Axes.matshow tries to set the figure aspect ratio to be the one of the array, strange things may happen if you reuse an existing figure. Returns
AxesImage
Other Parameters
**kwargsimshow arguments
Examples using matplotlib.pyplot.matshow
Matshow
|
matplotlib._as_gen.matplotlib.pyplot.matshow
|
matplotlib.pyplot.minorticks_off matplotlib.pyplot.minorticks_off()[source]
Remove minor ticks from the Axes.
|
matplotlib._as_gen.matplotlib.pyplot.minorticks_off
|
matplotlib.pyplot.minorticks_on matplotlib.pyplot.minorticks_on()[source]
Display minor ticks on the Axes. Displaying minor ticks may reduce performance; you may turn them off using minorticks_off() if drawing speed is a problem.
|
matplotlib._as_gen.matplotlib.pyplot.minorticks_on
|
matplotlib.pyplot.new_figure_manager matplotlib.pyplot.new_figure_manager(num, *args, **kwargs)[source]
Create a new figure manager instance.
|
matplotlib._as_gen.matplotlib.pyplot.new_figure_manager
|
matplotlib.pyplot.nipy_spectral matplotlib.pyplot.nipy_spectral()[source]
Set the colormap to 'nipy_spectral'. This changes the default colormap as well as the colormap of the current image if there is one. See help(colormaps) for more information.
|
matplotlib._as_gen.matplotlib.pyplot.nipy_spectral
|
matplotlib.pyplot.pause matplotlib.pyplot.pause(interval)[source]
Run the GUI event loop for interval seconds. If there is an active figure, it will be updated and displayed before the pause, and the GUI event loop (if any) will run during the pause. This can be used for crude animation. For more complex animation use matplotlib.animation. If there is no active figure, sleep for interval seconds instead. See also matplotlib.animation
Proper animations show
Show all figures and optional block until all figures are closed.
Examples using matplotlib.pyplot.pause
pyplot animation
Rotating a 3D plot
Rotating 3D wireframe plot
Faster rendering by using blitting
|
matplotlib._as_gen.matplotlib.pyplot.pause
|
matplotlib.pyplot.pcolor matplotlib.pyplot.pcolor(*args, shading=None, alpha=None, norm=None, cmap=None, vmin=None, vmax=None, data=None, **kwargs)[source]
Create a pseudocolor plot with a non-regular rectangular grid. Call signature: pcolor([X, Y,] C, **kwargs)
X and Y can be used to specify the corners of the quadrilaterals. Hint pcolor() can be very slow for large arrays. In most cases you should use the similar but much faster pcolormesh instead. See Differences between pcolor() and pcolormesh() for a discussion of the differences. Parameters
C2D array-like
The color-mapped values.
X, Yarray-like, optional
The coordinates of the corners of quadrilaterals of a pcolormesh: (X[i+1, j], Y[i+1, j]) (X[i+1, j+1], Y[i+1, j+1])
+-----+
| |
+-----+
(X[i, j], Y[i, j]) (X[i, j+1], Y[i, j+1])
Note that the column index corresponds to the x-coordinate, and the row index corresponds to y. For details, see the Notes section below. If shading='flat' the dimensions of X and Y should be one greater than those of C, and the quadrilateral is colored due to the value at C[i, j]. If X, Y and C have equal dimensions, a warning will be raised and the last row and column of C will be ignored. If shading='nearest', the dimensions of X and Y should be the same as those of C (if not, a ValueError will be raised). The color C[i, j] will be centered on (X[i, j], Y[i, j]). If X and/or Y are 1-D arrays or column vectors they will be expanded as needed into the appropriate 2D arrays, making a rectangular grid.
shading{'flat', 'nearest', 'auto'}, default: rcParams["pcolor.shading"] (default: 'auto')
The fill style for the quadrilateral. Possible values: 'flat': A solid color is used for each quad. The color of the quad (i, j), (i+1, j), (i, j+1), (i+1, j+1) is given by C[i, j]. The dimensions of X and Y should be one greater than those of C; if they are the same as C, then a deprecation warning is raised, and the last row and column of C are dropped. 'nearest': Each grid point will have a color centered on it, extending halfway between the adjacent grid centers. The dimensions of X and Y must be the same as C. 'auto': Choose 'flat' if dimensions of X and Y are one larger than C. Choose 'nearest' if dimensions are the same. See pcolormesh grids and shading for more description.
cmapstr or Colormap, default: rcParams["image.cmap"] (default: 'viridis')
A Colormap instance or registered colormap name. The colormap maps the C values to colors.
normNormalize, optional
The Normalize instance scales the data values to the canonical colormap range [0, 1] for mapping to colors. By default, the data range is mapped to the colorbar range using linear scaling.
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 C in case of the default linear scaling). It is an error to use vmin/vmax when norm is given.
edgecolors{'none', None, 'face', color, color sequence}, optional
The color of the edges. Defaults to 'none'. Possible values: 'none' or '': No edge.
None: rcParams["patch.edgecolor"] (default: 'black') will be used. Note that currently rcParams["patch.force_edgecolor"] (default: False) has to be True for this to work. 'face': Use the adjacent face color. A color or sequence of colors will set the edge color. The singular form edgecolor works as an alias.
alphafloat, default: None
The alpha blending value of the face color, between 0 (transparent) and 1 (opaque). Note: The edgecolor is currently not affected by this.
snapbool, default: False
Whether to snap the mesh to pixel boundaries. Returns
matplotlib.collections.Collection
Other Parameters
antialiasedsbool, default: False
The default antialiaseds is False if the default edgecolors="none" is used. This eliminates artificial lines at patch boundaries, and works regardless of the value of alpha. If edgecolors is not "none", then the default antialiaseds is taken from rcParams["patch.antialiased"] (default: True). Stroking the edges may be preferred if alpha is 1, but will cause artifacts otherwise.
dataindexable object, optional
If given, all parameters also accept a string s, which is interpreted as data[s] (unless this raises an exception). **kwargs
Additionally, the following arguments are allowed. They are passed along to the PolyCollection constructor:
Property Description
agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha array-like or scalar or None
animated bool
antialiased or aa or antialiaseds bool or list of bools
array array-like or None
capstyle CapStyle or {'butt', 'projecting', 'round'}
clim (vmin: float, vmax: float)
clip_box Bbox
clip_on bool
clip_path Patch or (Path, Transform) or None
cmap Colormap or str or None
color color or list of rgba tuples
edgecolor or ec or edgecolors color or list of colors or 'face'
facecolor or facecolors or fc color or list of colors
figure Figure
gid str
hatch {'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
in_layout bool
joinstyle JoinStyle or {'miter', 'round', 'bevel'}
label object
linestyle or dashes or linestyles or ls str or tuple or list thereof
linewidth or linewidths or lw float or list of floats
norm Normalize or None
offset_transform Transform
offsets (N, 2) or (2,) array-like
path_effects AbstractPathEffect
paths list of array-like
picker None or bool or float or callable
pickradius float
rasterized bool
sizes ndarray or None
sketch_params (scale: float, length: float, randomness: float)
snap bool or None
transform Transform
url str
urls list of str or None
verts list of array-like
verts_and_codes unknown
visible bool
zorder float See also pcolormesh
for an explanation of the differences between pcolor and pcolormesh. imshow
If X and Y are each equidistant, imshow can be a faster alternative. Notes Masked arrays X, Y and C may be masked arrays. If either C[i, j], or one of the vertices surrounding C[i, j] (X or Y at [i, j], [i+1, j], [i, j+1], [i+1, j+1]) is masked, nothing is plotted. Grid orientation The grid orientation follows the standard matrix convention: An array C with shape (nrows, ncolumns) is plotted with the column number as X and the row number as Y.
|
matplotlib._as_gen.matplotlib.pyplot.pcolor
|
matplotlib.pyplot.pcolormesh matplotlib.pyplot.pcolormesh(*args, alpha=None, norm=None, cmap=None, vmin=None, vmax=None, shading=None, antialiased=False, data=None, **kwargs)[source]
Create a pseudocolor plot with a non-regular rectangular grid. Call signature: pcolormesh([X, Y,] C, **kwargs)
X and Y can be used to specify the corners of the quadrilaterals. Hint pcolormesh is similar to pcolor. It is much faster and preferred in most cases. For a detailed discussion on the differences see Differences between pcolor() and pcolormesh(). Parameters
C2D array-like
The color-mapped values.
X, Yarray-like, optional
The coordinates of the corners of quadrilaterals of a pcolormesh: (X[i+1, j], Y[i+1, j]) (X[i+1, j+1], Y[i+1, j+1])
+-----+
| |
+-----+
(X[i, j], Y[i, j]) (X[i, j+1], Y[i, j+1])
Note that the column index corresponds to the x-coordinate, and the row index corresponds to y. For details, see the Notes section below. If shading='flat' the dimensions of X and Y should be one greater than those of C, and the quadrilateral is colored due to the value at C[i, j]. If X, Y and C have equal dimensions, a warning will be raised and the last row and column of C will be ignored. If shading='nearest' or 'gouraud', the dimensions of X and Y should be the same as those of C (if not, a ValueError will be raised). For 'nearest' the color C[i, j] is centered on (X[i, j], Y[i, j]). For 'gouraud', a smooth interpolation is caried out between the quadrilateral corners. If X and/or Y are 1-D arrays or column vectors they will be expanded as needed into the appropriate 2D arrays, making a rectangular grid.
cmapstr or Colormap, default: rcParams["image.cmap"] (default: 'viridis')
A Colormap instance or registered colormap name. The colormap maps the C values to colors.
normNormalize, optional
The Normalize instance scales the data values to the canonical colormap range [0, 1] for mapping to colors. By default, the data range is mapped to the colorbar range using linear scaling.
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 C in case of the default linear scaling). It is an error to use vmin/vmax when norm is given.
edgecolors{'none', None, 'face', color, color sequence}, optional
The color of the edges. Defaults to 'none'. Possible values: 'none' or '': No edge.
None: rcParams["patch.edgecolor"] (default: 'black') will be used. Note that currently rcParams["patch.force_edgecolor"] (default: False) has to be True for this to work. 'face': Use the adjacent face color. A color or sequence of colors will set the edge color. The singular form edgecolor works as an alias.
alphafloat, default: None
The alpha blending value, between 0 (transparent) and 1 (opaque).
shading{'flat', 'nearest', 'gouraud', 'auto'}, optional
The fill style for the quadrilateral; defaults to 'flat' or rcParams["pcolor.shading"] (default: 'auto'). Possible values: 'flat': A solid color is used for each quad. The color of the quad (i, j), (i+1, j), (i, j+1), (i+1, j+1) is given by C[i, j]. The dimensions of X and Y should be one greater than those of C; if they are the same as C, then a deprecation warning is raised, and the last row and column of C are dropped. 'nearest': Each grid point will have a color centered on it, extending halfway between the adjacent grid centers. The dimensions of X and Y must be the same as C. 'gouraud': Each quad will be Gouraud shaded: The color of the corners (i', j') are given by C[i', j']. The color values of the area in between is interpolated from the corner values. The dimensions of X and Y must be the same as C. When Gouraud shading is used, edgecolors is ignored. 'auto': Choose 'flat' if dimensions of X and Y are one larger than C. Choose 'nearest' if dimensions are the same. See pcolormesh grids and shading for more description.
snapbool, default: False
Whether to snap the mesh to pixel boundaries.
rasterizedbool, optional
Rasterize the pcolormesh when drawing vector graphics. This can speed up rendering and produce smaller files for large data sets. See also Rasterization for vector graphics. Returns
matplotlib.collections.QuadMesh
Other Parameters
dataindexable object, optional
If given, all parameters also accept a string s, which is interpreted as data[s] (unless this raises an exception). **kwargs
Additionally, the following arguments are allowed. They are passed along to the QuadMesh constructor:
Property Description
agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha array-like or scalar or None
animated bool
antialiased or aa or antialiaseds bool or list of bools
array (M, N) array-like or M*N array-like
capstyle CapStyle or {'butt', 'projecting', 'round'}
clim (vmin: float, vmax: float)
clip_box Bbox
clip_on bool
clip_path Patch or (Path, Transform) or None
cmap Colormap or str or None
color color or list of rgba tuples
edgecolor or ec or edgecolors color or list of colors or 'face'
facecolor or facecolors or fc color or list of colors
figure Figure
gid str
hatch {'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
in_layout bool
joinstyle JoinStyle or {'miter', 'round', 'bevel'}
label object
linestyle or dashes or linestyles or ls str or tuple or list thereof
linewidth or linewidths or lw float or list of floats
norm Normalize or None
offset_transform Transform
offsets (N, 2) or (2,) array-like
path_effects AbstractPathEffect
picker None or bool or float or callable
pickradius float
rasterized bool
sketch_params (scale: float, length: float, randomness: float)
snap bool or None
transform Transform
url str
urls list of str or None
visible bool
zorder float See also pcolor
An alternative implementation with slightly different features. For a detailed discussion on the differences see Differences between pcolor() and pcolormesh(). imshow
If X and Y are each equidistant, imshow can be a faster alternative. Notes Masked arrays C may be a masked array. If C[i, j] is masked, the corresponding quadrilateral will be transparent. Masking of X and Y is not supported. Use pcolor if you need this functionality. Grid orientation The grid orientation follows the standard matrix convention: An array C with shape (nrows, ncolumns) is plotted with the column number as X and the row number as Y. Differences between pcolor() and pcolormesh() Both methods are used to create a pseudocolor plot of a 2D array using quadrilaterals. The main difference lies in the created object and internal data handling: While pcolor returns a PolyCollection, pcolormesh returns a QuadMesh. The latter is more specialized for the given purpose and thus is faster. It should almost always be preferred. There is also a slight difference in the handling of masked arrays. Both pcolor and pcolormesh support masked arrays for C. However, only pcolor supports masked arrays for X and Y. The reason lies in the internal handling of the masked values. pcolor leaves out the respective polygons from the PolyCollection. pcolormesh sets the facecolor of the masked elements to transparent. You can see the difference when using edgecolors. While all edges are drawn irrespective of masking in a QuadMesh, the edge between two adjacent masked quadrilaterals in pcolor is not drawn as the corresponding polygons do not exist in the PolyCollection. Another difference is the support of Gouraud shading in pcolormesh, which is not available with pcolor.
|
matplotlib._as_gen.matplotlib.pyplot.pcolormesh
|
matplotlib.pyplot.phase_spectrum matplotlib.pyplot.phase_spectrum(x, Fs=None, Fc=None, window=None, pad_to=None, sides=None, *, data=None, **kwargs)[source]
Plot the phase spectrum. Compute the phase spectrum (unwrapped angle spectrum) of x. Data is padded to a length of pad_to and the windowing function window is applied to the signal. Parameters
x1-D array or sequence
Array or sequence 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. While not increasing the actual resolution of the spectrum (the minimum distance between resolvable peaks), this can give more points in the plot, allowing for more detail. This corresponds to the n parameter in the call to fft(). The default is None, which sets pad_to equal to the length of the input signal (i.e. no padding).
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. Returns
spectrum1-D array
The values for the phase spectrum in radians (real valued).
freqs1-D array
The frequencies corresponding to the elements in spectrum.
lineLine2D
The line created by this function. 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 **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 magnitude_spectrum
Plots the magnitudes of the corresponding frequencies. angle_spectrum
Plots the wrapped version of this function. specgram
Can plot the phase spectrum of segments within the signal in a colormap.
|
matplotlib._as_gen.matplotlib.pyplot.phase_spectrum
|
matplotlib.pyplot.pie matplotlib.pyplot.pie(x, explode=None, labels=None, colors=None, autopct=None, pctdistance=0.6, shadow=False, labeldistance=1.1, startangle=0, radius=1, counterclock=True, wedgeprops=None, textprops=None, center=(0, 0), frame=False, rotatelabels=False, *, normalize=True, data=None)[source]
Plot a pie chart. Make a pie chart of array x. The fractional area of each wedge is given by x/sum(x). If sum(x) < 1, then the values of x give the fractional area directly and the array will not be normalized. The resulting pie will have an empty wedge of size 1 - sum(x). The wedges are plotted counterclockwise, by default starting from the x-axis. Parameters
x1D array-like
The wedge sizes.
explodearray-like, default: None
If not None, is a len(x) array which specifies the fraction of the radius with which to offset each wedge.
labelslist, default: None
A sequence of strings providing the labels for each wedge
colorsarray-like, default: None
A sequence of colors through which the pie chart will cycle. If None, will use the colors in the currently active cycle.
autopctNone or str or callable, default: None
If not None, is a string or function used to label the wedges with their numeric value. The label will be placed inside the wedge. If it is a format string, the label will be fmt % pct. If it is a function, it will be called.
pctdistancefloat, default: 0.6
The ratio between the center of each pie slice and the start of the text generated by autopct. Ignored if autopct is None.
shadowbool, default: False
Draw a shadow beneath the pie.
normalizebool, default: True
When True, always make a full pie by normalizing x so that sum(x) == 1. False makes a partial pie if sum(x) <= 1 and raises a ValueError for sum(x) > 1.
labeldistancefloat or None, default: 1.1
The radial distance at which the pie labels are drawn. If set to None, label are not drawn, but are stored for use in legend()
startanglefloat, default: 0 degrees
The angle by which the start of the pie is rotated, counterclockwise from the x-axis.
radiusfloat, default: 1
The radius of the pie.
counterclockbool, default: True
Specify fractions direction, clockwise or counterclockwise.
wedgepropsdict, default: None
Dict of arguments passed to the wedge objects making the pie. For example, you can pass in wedgeprops = {'linewidth': 3} to set the width of the wedge border lines equal to 3. For more details, look at the doc/arguments of the wedge object. By default clip_on=False.
textpropsdict, default: None
Dict of arguments to pass to the text objects.
center(float, float), default: (0, 0)
The coordinates of the center of the chart.
framebool, default: False
Plot Axes frame with the chart if true.
rotatelabelsbool, default: False
Rotate each label to the angle of the corresponding slice if true.
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, explode, labels, colors Returns
patcheslist
A sequence of matplotlib.patches.Wedge instances
textslist
A list of the label Text instances.
autotextslist
A list of Text instances for the numeric labels. This will only be returned if the parameter autopct is not None. Notes The pie chart will probably look best if the figure and Axes are square, or the Axes aspect is equal. This method sets the aspect ratio of the axis to "equal". The Axes aspect ratio can be controlled with Axes.set_aspect.
|
matplotlib._as_gen.matplotlib.pyplot.pie
|
matplotlib.pyplot.pink matplotlib.pyplot.pink()[source]
Set the colormap to 'pink'. This changes the default colormap as well as the colormap of the current image if there is one. See help(colormaps) for more information.
|
matplotlib._as_gen.matplotlib.pyplot.pink
|
matplotlib.pyplot.plasma matplotlib.pyplot.plasma()[source]
Set the colormap to 'plasma'. This changes the default colormap as well as the colormap of the current image if there is one. See help(colormaps) for more information.
|
matplotlib._as_gen.matplotlib.pyplot.plasma
|
matplotlib.pyplot.plot matplotlib.pyplot.plot(*args, scalex=True, scaley=True, data=None, **kwargs)[source]
Plot y versus x as lines and/or markers. Call signatures: plot([x], y, [fmt], *, data=None, **kwargs)
plot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)
The coordinates of the points or line nodes are given by x, y. The optional parameter fmt is a convenient way for defining basic formatting like color, marker and linestyle. It's a shortcut string notation described in the Notes section below. >>> plot(x, y) # plot x and y using default line style and color
>>> plot(x, y, 'bo') # plot x and y using blue circle markers
>>> plot(y) # plot y using x as index array 0..N-1
>>> plot(y, 'r+') # ditto, but with red plusses
You can use Line2D properties as keyword arguments for more control on the appearance. Line properties and fmt can be mixed. The following two calls yield identical results: >>> plot(x, y, 'go--', linewidth=2, markersize=12)
>>> plot(x, y, color='green', marker='o', linestyle='dashed',
... linewidth=2, markersize=12)
When conflicting with fmt, keyword arguments take precedence. Plotting labelled data There's a convenient way for plotting objects with labelled data (i.e. data that can be accessed by index obj['y']). Instead of giving the data in x and y, you can provide the object in the data parameter and just give the labels for x and y: >>> plot('xlabel', 'ylabel', data=obj)
All indexable objects are supported. This could e.g. be a dict, a pandas.DataFrame or a structured numpy array. Plotting multiple sets of data There are various ways to plot multiple sets of data.
The most straight forward way is just to call plot multiple times. Example: >>> plot(x1, y1, 'bo')
>>> plot(x2, y2, 'go')
If x and/or y are 2D arrays a separate data set will be drawn for every column. If both x and y are 2D, they must have the same shape. If only one of them is 2D with shape (N, m) the other must have length N and will be used for every data set m. Example: >>> x = [1, 2, 3]
>>> y = np.array([[1, 2], [3, 4], [5, 6]])
>>> plot(x, y)
is equivalent to: >>> for col in range(y.shape[1]):
... plot(x, y[:, col])
The third way is to specify multiple sets of [x], y, [fmt] groups: >>> plot(x1, y1, 'g^', x2, y2, 'g-')
In this case, any additional keyword argument applies to all datasets. Also this syntax cannot be combined with the data parameter. By default, each line is assigned a different style specified by a 'style cycle'. The fmt and line property parameters are only necessary if you want explicit deviations from these defaults. Alternatively, you can also change the style cycle using rcParams["axes.prop_cycle"] (default: cycler('color', ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf'])). Parameters
x, yarray-like or scalar
The horizontal / vertical coordinates of the data points. x values are optional and default to range(len(y)). Commonly, these parameters are 1D arrays. They can also be scalars, or two-dimensional (in that case, the columns represent separate data sets). These arguments cannot be passed as keywords.
fmtstr, optional
A format string, e.g. 'ro' for red circles. See the Notes section for a full description of the format strings. Format strings are just an abbreviation for quickly setting basic line properties. All of these and more can also be controlled by keyword arguments. This argument cannot be passed as keyword.
dataindexable object, optional
An object with labelled data. If given, provide the label names to plot in x and y. Note Technically there's a slight ambiguity in calls where the second label is a valid fmt. plot('n', 'o', data=obj) could be plt(x, y) or plt(y, fmt). In such cases, the former interpretation is chosen, but a warning is issued. You may suppress the warning by adding an empty format string plot('n', 'o', '', data=obj). Returns
list of Line2D
A list of lines representing the plotted data. Other Parameters
scalex, scaleybool, default: True
These parameters determine if the view limits are adapted to the data limits. The values are passed on to autoscale_view.
**kwargsLine2D properties, optional
kwargs are used to specify properties like a line label (for auto legends), linewidth, antialiasing, marker face color. Example: >>> plot([1, 2, 3], [1, 2, 3], 'go-', label='line 1', linewidth=2)
>>> plot([1, 2, 3], [1, 4, 9], 'rs', label='line 2')
If you specify multiple lines with one plot call, the kwargs apply to all those lines. In case the label object is iterable, each element is used as labels for each set of data. Here is a list of available Line2D properties:
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 scatter
XY scatter plot with markers of varying size and/or color ( sometimes also called bubble chart). Notes Format Strings A format string consists of a part for color, marker and line: fmt = '[marker][line][color]'
Each of them is optional. If not provided, the value from the style cycle is used. Exception: If line is given, but no marker, the data will be a line without markers. Other combinations such as [color][marker][line] are also supported, but note that their parsing may be ambiguous. Markers
character description
'.' point marker
',' pixel marker
'o' circle marker
'v' triangle_down marker
'^' triangle_up marker
'<' triangle_left marker
'>' triangle_right marker
'1' tri_down marker
'2' tri_up marker
'3' tri_left marker
'4' tri_right marker
'8' octagon marker
's' square marker
'p' pentagon marker
'P' plus (filled) marker
'*' star marker
'h' hexagon1 marker
'H' hexagon2 marker
'+' plus marker
'x' x marker
'X' x (filled) marker
'D' diamond marker
'd' thin_diamond marker
'|' vline marker
'_' hline marker Line Styles
character description
'-' solid line style
'--' dashed line style
'-.' dash-dot line style
':' dotted line style Example format strings: 'b' # blue markers with default shape
'or' # red circles
'-g' # green solid line
'--' # dashed line with default color
'^k:' # black triangle_up markers connected by a dotted line
Colors The supported color abbreviations are the single letter codes
character color
'b' blue
'g' green
'r' red
'c' cyan
'm' magenta
'y' yellow
'k' black
'w' white and the 'CN' colors that index into the default property cycle. If the color is the only part of the format string, you can additionally use any matplotlib.colors spec, e.g. full names ('green') or hex strings ('#008000').
Examples using matplotlib.pyplot.plot
Plotting masked and NaN values
Scatter Masked
Stairs Demo
Step Demo
Custom Figure subclasses
Managing multiple figures in pyplot
Shared Axis
Multiple subplots
Controlling style of text and labels using a dictionary
Title positioning
Infinite lines
plot() format string
Pyplot Mathtext
Pyplot Simple
Pyplot Three
Pyplot Two Subplots
Dolphins
Solarized Light stylesheet
Frame grabbing
Coords Report
Customize Rc
Findobj Demo
Multipage PDF
Print Stdout
Set and get properties
transforms.offset_copy
Zorder Demo
Custom scale
Placing date ticks using recurrence rules
Rotating custom tick labels
Tool Manager
Buttons
Slider
Snapping Sliders to Discrete Values
Basic Usage
Pyplot tutorial
Customizing Matplotlib with style sheets and rcParams
Path effects guide
|
matplotlib._as_gen.matplotlib.pyplot.plot
|
matplotlib.pyplot.plot_date matplotlib.pyplot.plot_date(x, y, fmt='o', tz=None, xdate=True, ydate=False, *, data=None, **kwargs)[source]
Plot coercing the axis to treat floats as dates. Discouraged This method exists for historic reasons and will be deprecated in the future.
datetime-like data should directly be plotted using plot. If you need to plot plain numeric data as Matplotlib date format or need to set a timezone, call ax.xaxis.axis_date / ax.yaxis.axis_date before plot. See Axis.axis_date. Similar to plot, this plots y vs. x as lines or markers. However, the axis labels are formatted as dates depending on xdate and ydate. Note that plot will work with datetime and numpy.datetime64 objects without resorting to this method. Parameters
x, yarray-like
The coordinates of the data points. If xdate or ydate is True, the respective values x or y are interpreted as Matplotlib dates.
fmtstr, optional
The plot format string. For details, see the corresponding parameter in plot.
tztimezone string or datetime.tzinfo, default: rcParams["timezone"] (default: 'UTC')
The time zone to use in labeling dates.
xdatebool, default: True
If True, the x-axis will be interpreted as Matplotlib dates.
ydatebool, default: False
If True, the y-axis will be interpreted as Matplotlib dates. Returns
list of Line2D
Objects representing the plotted data. 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 matplotlib.dates
Helper functions on dates. matplotlib.dates.date2num
Convert dates to num. matplotlib.dates.num2date
Convert num to dates. matplotlib.dates.drange
Create an equally spaced sequence of dates. Notes If you are using custom date tickers and formatters, it may be necessary to set the formatters/locators after the call to plot_date. plot_date will set the default tick locator to AutoDateLocator (if the tick locator is not already set to a DateLocator instance) and the default tick formatter to AutoDateFormatter (if the tick formatter is not already set to a DateFormatter instance).
|
matplotlib._as_gen.matplotlib.pyplot.plot_date
|
matplotlib.pyplot.plotting()[source]
Function Description
acorr Plot the autocorrelation of x.
angle_spectrum Plot the angle spectrum.
annotate Annotate the point xy with text text.
arrow Add an arrow to the Axes.
autoscale Autoscale the axis view to the data (toggle).
axes Add an axes to the current figure and make it the current axes.
axhline Add a horizontal line across the axis.
axhspan Add a horizontal span (rectangle) across the Axes.
axis Convenience method to get or set some axis properties.
axline Add an infinitely long straight line.
axvline Add a vertical line across the Axes.
axvspan Add a vertical span (rectangle) across the Axes.
bar Make a bar plot.
bar_label Label a bar plot.
barbs Plot a 2D field of barbs.
barh Make a horizontal bar plot.
box Turn the axes box on or off on the current axes.
boxplot Draw a box and whisker plot.
broken_barh Plot a horizontal sequence of rectangles.
cla Clear the current axes.
clabel Label a contour plot.
clf Clear the current figure.
clim Set the color limits of the current image.
close Close a figure window.
cohere Plot the coherence between x and y.
colorbar Add a colorbar to a plot.
contour Plot contour lines.
contourf Plot filled contours.
csd Plot the cross-spectral density.
delaxes Remove an Axes (defaulting to the current axes) from its figure.
draw Redraw the current figure.
draw_if_interactive Redraw the current figure if in interactive mode.
errorbar Plot y versus x as lines and/or markers with attached errorbars.
eventplot Plot identical parallel lines at the given positions.
figimage Add a non-resampled image to the figure.
figlegend Place a legend on the figure.
fignum_exists Return whether the figure with the given id exists.
figtext Add text to figure.
figure Create a new figure, or activate an existing figure.
fill Plot filled polygons.
fill_between Fill the area between two horizontal curves.
fill_betweenx Fill the area between two vertical curves.
findobj Find artist objects.
gca Get the current Axes.
gcf Get the current figure.
gci Get the current colorable artist.
get Return the value of an Artist's property, or print all of them.
get_figlabels Return a list of existing figure labels.
get_fignums Return a list of existing figure numbers.
getp Return the value of an Artist's property, or print all of them.
grid Configure the grid lines.
hexbin Make a 2D hexagonal binning plot of points x, y.
hist Plot a histogram.
hist2d Make a 2D histogram plot.
hlines Plot horizontal lines at each y from xmin to xmax.
imread Read an image from a file into an array.
imsave Save an array as an image file.
imshow Display data as an image, i.e., on a 2D regular raster.
install_repl_displayhook Install a repl display hook so that any stale figure are automatically redrawn when control is returned to the repl.
ioff Disable interactive mode.
ion Enable interactive mode.
isinteractive Return whether plots are updated after every plotting command.
legend Place a legend on the Axes.
locator_params Control behavior of major tick locators.
loglog Make a plot with log scaling on both the x and y axis.
magnitude_spectrum Plot the magnitude spectrum.
margins Set or retrieve autoscaling margins.
matshow Display an array as a matrix in a new figure window.
minorticks_off Remove minor ticks from the Axes.
minorticks_on Display minor ticks on the Axes.
new_figure_manager Create a new figure manager instance.
pause Run the GUI event loop for interval seconds.
pcolor Create a pseudocolor plot with a non-regular rectangular grid.
pcolormesh Create a pseudocolor plot with a non-regular rectangular grid.
phase_spectrum Plot the phase spectrum.
pie Plot a pie chart.
plot Plot y versus x as lines and/or markers.
plot_date Plot coercing the axis to treat floats as dates.
polar Make a polar plot.
psd Plot the power spectral density.
quiver Plot a 2D field of arrows.
quiverkey Add a key to a quiver plot.
rc Set the current rcParams.
rc_context Return a context manager for temporarily changing rcParams.
rcdefaults Restore the rcParams from Matplotlib's internal default style.
rgrids Get or set the radial gridlines on the current polar plot.
savefig Save the current figure.
sca Set the current Axes to ax and the current Figure to the parent of ax.
scatter A scatter plot of y vs.
sci Set the current image.
semilogx Make a plot with log scaling on the x axis.
semilogy Make a plot with log scaling on the y axis.
set_cmap Set the default colormap, and applies it to the current image if any.
set_loglevel Set Matplotlib's root logger and root logger handler level, creating the handler if it does not exist yet.
setp Set one or more properties on an Artist, or list allowed values.
show Display all open figures.
specgram Plot a spectrogram.
spy Plot the sparsity pattern of a 2D array.
stackplot Draw a stacked area plot.
stairs A stepwise constant function as a line with bounding edges or a filled plot.
stem Create a stem plot.
step Make a step plot.
streamplot Draw streamlines of a vector flow.
subplot Add an Axes to the current figure or retrieve an existing Axes.
subplot2grid Create a subplot at a specific location inside a regular grid.
subplot_mosaic Build a layout of Axes based on ASCII art or nested lists.
subplot_tool Launch a subplot tool window for a figure.
subplots Create a figure and a set of subplots.
subplots_adjust Adjust the subplot layout parameters.
suptitle Add a centered suptitle to the figure.
switch_backend Close all open figures and set the Matplotlib backend.
table Add a table to an Axes.
text Add text to the Axes.
thetagrids Get or set the theta gridlines on the current polar plot.
tick_params Change the appearance of ticks, tick labels, and gridlines.
ticklabel_format Configure the ScalarFormatter used by default for linear axes.
tight_layout Adjust the padding between and around subplots.
title Set a title for the Axes.
tricontour Draw contour lines on an unstructured triangular grid.
tricontourf Draw contour regions on an unstructured triangular grid.
tripcolor Create a pseudocolor plot of an unstructured triangular grid.
triplot Draw a unstructured triangular grid as lines and/or markers.
twinx Make and return a second axes that shares the x-axis.
twiny Make and return a second axes that shares the y-axis.
uninstall_repl_displayhook Uninstall the Matplotlib display hook.
violinplot Make a violin plot.
vlines Plot vertical lines at each x from ymin to ymax.
xcorr Plot the cross correlation between x and y.
xkcd Turn on xkcd sketch-style drawing mode.
xlabel Set the label for the x-axis.
xlim Get or set the x limits of the current axes.
xscale Set the x-axis scale.
xticks Get or set the current tick locations and labels of the x-axis.
ylabel Set the label for the y-axis.
ylim Get or set the y-limits of the current axes.
yscale Set the y-axis scale.
yticks Get or set the current tick locations and labels of the y-axis.
|
matplotlib.pyplot_summary#matplotlib.pyplot.plotting
|
matplotlib.pyplot.polar matplotlib.pyplot.polar(*args, **kwargs)[source]
Make a polar plot. call signature: polar(theta, r, **kwargs)
Multiple theta, r arguments are supported, with format strings, as in plot.
Examples using matplotlib.pyplot.polar
transforms.offset_copy
|
matplotlib._as_gen.matplotlib.pyplot.polar
|
matplotlib.pyplot.prism matplotlib.pyplot.prism()[source]
Set the colormap to 'prism'. This changes the default colormap as well as the colormap of the current image if there is one. See help(colormaps) for more information.
|
matplotlib._as_gen.matplotlib.pyplot.prism
|
matplotlib.pyplot.psd matplotlib.pyplot.psd(x, 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 power spectral density. The power spectral density \(P_{xx}\) by Welch's average periodogram method. The vector x is divided into NFFT length segments. Each segment is detrended by function detrend and windowed by function window. noverlap gives the length of the overlap between segments. The \(|\mathrm{fft}(i)|^2\) of each segment \(i\) are averaged to compute \(P_{xx}\), with a scaling to correct for power loss due to windowing. If len(x) < NFFT, it will be zero padded to NFFT. Parameters
x1-D array or sequence
Array or sequence 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
Pxx1-D array
The values for the power spectrum \(P_{xx}\) before scaling (real valued).
freqs1-D array
The frequencies corresponding to the elements in Pxx.
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 **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 specgram
Differs in the default overlap; in not returning the mean of the segment periodograms; in returning the times of the segments; and in plotting a colormap instead of a line. magnitude_spectrum
Plots the magnitude spectrum. csd
Plots the spectral density between two signals. Notes For plotting, the power is plotted as \(10\log_{10}(P_{xx})\) for decibels, though Pxx itself is returned. References Bendat & Piersol -- Random Data: Analysis and Measurement Procedures, John Wiley & Sons (1986)
|
matplotlib._as_gen.matplotlib.pyplot.psd
|
matplotlib.pyplot.quiver matplotlib.pyplot.quiver(*args, data=None, **kwargs)[source]
Plot a 2D field of arrows. Call signature: quiver([X, Y], U, V, [C], **kw)
X, Y define the arrow locations, U, V define the arrow directions, and C optionally sets the color. Each arrow is internally represented by a filled polygon with a default edge linewidth of 0. As a result, an arrow is rather a filled area, not a line with a head, and PolyCollection properties like linewidth, linestyle, facecolor, etc. act accordingly. Arrow size The default settings auto-scales the length of the arrows to a reasonable size. To change this behavior see the scale and scale_units parameters. Arrow shape The defaults give a slightly swept-back arrow; to make the head a triangle, make headaxislength the same as headlength. To make the arrow more pointed, reduce headwidth or increase headlength and headaxislength. To make the head smaller relative to the shaft, scale down all the head parameters. You will probably do best to leave minshaft alone. Arrow outline linewidths and edgecolors can be used to customize the arrow outlines. Parameters
X, Y1D or 2D array-like, optional
The x and y coordinates of the arrow locations. If not given, they will be generated as a uniform integer meshgrid based on the dimensions of U and V. If X and Y are 1D but U, V are 2D, X, Y are expanded to 2D using X, Y = np.meshgrid(X, Y). In this case len(X) and len(Y) must match the column and row dimensions of U and V.
U, V1D or 2D array-like
The x and y direction components of the arrow vectors. They must have the same number of elements, matching the number of arrow locations. U and V may be masked. Only locations unmasked in U, V, and C will be drawn.
C1D or 2D array-like, optional
Numeric data that defines the arrow colors by colormapping via norm and cmap. This does not support explicit colors. If you want to set colors directly, use color instead. The size of C must match the number of arrow locations.
units{'width', 'height', 'dots', 'inches', 'x', 'y', 'xy'}, default: 'width'
The arrow dimensions (except for length) are measured in multiples of this unit. The following values are supported: 'width', 'height': The width or height of the axis. 'dots', 'inches': Pixels or inches based on the figure dpi. 'x', 'y', 'xy': X, Y or \(\sqrt{X^2 + Y^2}\) in data units. The arrows scale differently depending on the units. For 'x' or 'y', the arrows get larger as one zooms in; for other units, the arrow size is independent of the zoom state. For 'width or 'height', the arrow size increases with the width and height of the axes, respectively, when the window is resized; for 'dots' or 'inches', resizing does not change the arrows.
angles{'uv', 'xy'} or array-like, default: 'uv'
Method for determining the angle of the arrows.
'uv': The arrow axis aspect ratio is 1 so that if U == V the orientation of the arrow on the plot is 45 degrees counter-clockwise from the horizontal axis (positive to the right). Use this if the arrows symbolize a quantity that is not based on X, Y data coordinates. 'xy': Arrows point from (x, y) to (x+u, y+v). Use this for plotting a gradient field, for example.
Alternatively, arbitrary angles may be specified explicitly as an array of values in degrees, counter-clockwise from the horizontal axis. In this case U, V is only used to determine the length of the arrows. Note: inverting a data axis will correspondingly invert the arrows only with angles='xy'.
scalefloat, optional
Number of data units per arrow length unit, e.g., m/s per plot width; a smaller scale parameter makes the arrow longer. Default is None. If None, a simple autoscaling algorithm is used, based on the average vector length and the number of vectors. The arrow length unit is given by the scale_units parameter.
scale_units{'width', 'height', 'dots', 'inches', 'x', 'y', 'xy'}, optional
If the scale kwarg is None, the arrow length unit. Default is None. e.g. scale_units is 'inches', scale is 2.0, and (u, v) = (1, 0), then the vector will be 0.5 inches long. If scale_units is 'width' or 'height', then the vector will be half the width/height of the axes. If scale_units is 'x' then the vector will be 0.5 x-axis units. To plot vectors in the x-y plane, with u and v having the same units as x and y, use angles='xy', scale_units='xy', scale=1.
widthfloat, optional
Shaft width in arrow units; default depends on choice of units, above, and number of vectors; a typical starting value is about 0.005 times the width of the plot.
headwidthfloat, default: 3
Head width as multiple of shaft width.
headlengthfloat, default: 5
Head length as multiple of shaft width.
headaxislengthfloat, default: 4.5
Head length at shaft intersection.
minshaftfloat, default: 1
Length below which arrow scales, in units of head length. Do not set this to less than 1, or small arrows will look terrible!
minlengthfloat, default: 1
Minimum length as a multiple of shaft width; if an arrow length is less than this, plot a dot (hexagon) of this diameter instead.
pivot{'tail', 'mid', 'middle', 'tip'}, default: 'tail'
The part of the arrow that is anchored to the X, Y grid. The arrow rotates about this point. 'mid' is a synonym for 'middle'.
colorcolor or color sequence, optional
Explicit color(s) for the arrows. If C has been set, color has no effect. This is a synonym for the PolyCollection facecolor parameter. Returns
Quiver
Other Parameters
dataindexable object, optional
If given, all parameters also accept a string s, which is interpreted as data[s] (unless this raises an exception).
**kwargsPolyCollection properties, optional
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 Axes.quiverkey
Add a key to a quiver plot.
|
matplotlib._as_gen.matplotlib.pyplot.quiver
|
matplotlib.pyplot.quiverkey matplotlib.pyplot.quiverkey(Q, X, Y, U, label, **kwargs)[source]
Add a key to a quiver plot. The positioning of the key depends on X, Y, coordinates, and labelpos. If labelpos is 'N' or 'S', X, Y give the position of the middle of the key arrow. If labelpos is 'E', X, Y positions the head, and if labelpos is 'W', X, Y positions the tail; in either of these two cases, X, Y is somewhere in the middle of the arrow+label key object. Parameters
Qmatplotlib.quiver.Quiver
A Quiver object as returned by a call to quiver().
X, Yfloat
The location of the key.
Ufloat
The length of the key.
labelstr
The key label (e.g., length and units of the key).
anglefloat, default: 0
The angle of the key arrow, in degrees anti-clockwise from the x-axis.
coordinates{'axes', 'figure', 'data', 'inches'}, default: 'axes'
Coordinate system and units for X, Y: 'axes' and 'figure' are normalized coordinate systems with (0, 0) in the lower left and (1, 1) in the upper right; 'data' are the axes data coordinates (used for the locations of the vectors in the quiver plot itself); 'inches' is position in the figure in inches, with (0, 0) at the lower left corner.
colorcolor
Overrides face and edge colors from Q.
labelpos{'N', 'S', 'E', 'W'}
Position the label above, below, to the right, to the left of the arrow, respectively.
labelsepfloat, default: 0.1
Distance in inches between the arrow and the label.
labelcolorcolor, default: rcParams["text.color"] (default: 'black')
Label color.
fontpropertiesdict, optional
A dictionary with keyword arguments accepted by the FontProperties initializer: family, style, variant, size, weight. **kwargs
Any additional keyword arguments are used to override vector properties taken from Q.
|
matplotlib._as_gen.matplotlib.pyplot.quiverkey
|
matplotlib.pyplot.rc matplotlib.pyplot.rc(group, **kwargs)[source]
Set the current rcParams. group is the grouping for the rc, e.g., for lines.linewidth the group is lines, for axes.facecolor, the group is axes, and so on. Group may also be a list or tuple of group names, e.g., (xtick, ytick). kwargs is a dictionary attribute name/value pairs, e.g.,: rc('lines', linewidth=2, color='r')
sets the current rcParams and is equivalent to: rcParams['lines.linewidth'] = 2
rcParams['lines.color'] = 'r'
The following aliases are available to save typing for interactive users:
Alias Property
'lw' 'linewidth'
'ls' 'linestyle'
'c' 'color'
'fc' 'facecolor'
'ec' 'edgecolor'
'mew' 'markeredgewidth'
'aa' 'antialiased' Thus you could abbreviate the above call as: rc('lines', lw=2, c='r')
Note you can use python's kwargs dictionary facility to store dictionaries of default parameters. e.g., you can customize the font rc as follows: font = {'family' : 'monospace',
'weight' : 'bold',
'size' : 'larger'}
rc('font', **font) # pass in the font dict as kwargs
This enables you to easily switch between several configurations. Use matplotlib.style.use('default') or rcdefaults() to restore the default rcParams after changes. Notes Similar functionality is available by using the normal dict interface, i.e. rcParams.update({"lines.linewidth": 2, ...}) (but rcParams.update does not support abbreviations or grouping).
Examples using matplotlib.pyplot.rc
Styling with cycler
|
matplotlib._as_gen.matplotlib.pyplot.rc
|
matplotlib.pyplot.rc_context matplotlib.pyplot.rc_context(rc=None, fname=None)[source]
Return a context manager for temporarily changing rcParams. Parameters
rcdict
The rcParams to temporarily set.
fnamestr or path-like
A file with Matplotlib rc settings. If both fname and rc are given, settings from rc take precedence. See also The matplotlibrc file
Examples Passing explicit values via a dict: with mpl.rc_context({'interactive': False}):
fig, ax = plt.subplots()
ax.plot(range(3), range(3))
fig.savefig('example.png')
plt.close(fig)
Loading settings from a file: with mpl.rc_context(fname='print.rc'):
plt.plot(x, y) # uses 'print.rc'
Examples using matplotlib.pyplot.rc_context
Style sheets reference
Matplotlib logo
|
matplotlib._as_gen.matplotlib.pyplot.rc_context
|
matplotlib.pyplot.rcdefaults matplotlib.pyplot.rcdefaults()[source]
Restore the rcParams from Matplotlib's internal default style. Style-blacklisted rcParams (defined in matplotlib.style.core.STYLE_BLACKLIST) are not updated. See also matplotlib.rc_file_defaults
Restore the rcParams from the rc file originally loaded by Matplotlib. matplotlib.style.use
Use a specific style file. Call style.use('default') to restore the default style.
Examples using matplotlib.pyplot.rcdefaults
Horizontal bar chart
Customize Rc
|
matplotlib._as_gen.matplotlib.pyplot.rcdefaults
|
matplotlib.pyplot.rgrids matplotlib.pyplot.rgrids(radii=None, labels=None, angle=None, fmt=None, **kwargs)[source]
Get or set the radial gridlines on the current polar plot. Call signatures: lines, labels = rgrids()
lines, labels = rgrids(radii, labels=None, angle=22.5, fmt=None, **kwargs)
When called with no arguments, rgrids simply returns the tuple (lines, labels). When called with arguments, the labels will appear at the specified radial distances and angle. Parameters
radiituple with floats
The radii for the radial gridlines
labelstuple with strings or None
The labels to use at each radial gridline. The matplotlib.ticker.ScalarFormatter will be used if None.
anglefloat
The angular position of the radius labels in degrees.
fmtstr or None
Format string used in matplotlib.ticker.FormatStrFormatter. For example '%f'. Returns
lineslist of lines.Line2D
The radial gridlines.
labelslist of text.Text
The tick labels. Other Parameters
**kwargs
kwargs are optional Text properties for the labels. See also pyplot.thetagrids
projections.polar.PolarAxes.set_rgrids
Axis.get_gridlines
Axis.get_ticklabels
Examples # set the locations of the radial gridlines
lines, labels = rgrids( (0.25, 0.5, 1.0) )
# set the locations and labels of the radial gridlines
lines, labels = rgrids( (0.25, 0.5, 1.0), ('Tom', 'Dick', 'Harry' ))
|
matplotlib._as_gen.matplotlib.pyplot.rgrids
|
matplotlib.pyplot.savefig matplotlib.pyplot.savefig(*args, **kwargs)[source]
Save the current figure. Call signature: savefig(fname, *, dpi='figure', format=None, metadata=None,
bbox_inches=None, pad_inches=0.1,
facecolor='auto', edgecolor='auto',
backend=None, **kwargs
)
The available output formats depend on the backend being used. Parameters
fnamestr or path-like or binary file-like
A path, or a Python file-like object, or possibly some backend-dependent object such as matplotlib.backends.backend_pdf.PdfPages. If format is set, it determines the output format, and the file is saved as fname. Note that fname is used verbatim, and there is no attempt to make the extension, if any, of fname match format, and no extension is appended. If format is not set, then the format is inferred from the extension of fname, if there is one. If format is not set and fname has no extension, then the file is saved with rcParams["savefig.format"] (default: 'png') and the appropriate extension is appended to fname. Other Parameters
dpifloat or 'figure', default: rcParams["savefig.dpi"] (default: 'figure')
The resolution in dots per inch. If 'figure', use the figure's dpi value.
formatstr
The file format, e.g. 'png', 'pdf', 'svg', ... The behavior when this is unset is documented under fname.
metadatadict, optional
Key/value pairs to store in the image metadata. The supported keys and defaults depend on the image format and backend: 'png' with Agg backend: See the parameter metadata of print_png. 'pdf' with pdf backend: See the parameter metadata of PdfPages. 'svg' with svg backend: See the parameter metadata of print_svg. 'eps' and 'ps' with PS backend: Only 'Creator' is supported.
bbox_inchesstr or Bbox, default: rcParams["savefig.bbox"] (default: None)
Bounding box in inches: only the given portion of the figure is saved. If 'tight', try to figure out the tight bbox of the figure.
pad_inchesfloat, default: rcParams["savefig.pad_inches"] (default: 0.1)
Amount of padding around the figure when bbox_inches is 'tight'.
facecolorcolor or 'auto', default: rcParams["savefig.facecolor"] (default: 'auto')
The facecolor of the figure. If 'auto', use the current figure facecolor.
edgecolorcolor or 'auto', default: rcParams["savefig.edgecolor"] (default: 'auto')
The edgecolor of the figure. If 'auto', use the current figure edgecolor.
backendstr, optional
Use a non-default backend to render the file, e.g. to render a png file with the "cairo" backend rather than the default "agg", or a pdf file with the "pgf" backend rather than the default "pdf". Note that the default backend is normally sufficient. See The builtin backends for a list of valid backends for each file format. Custom backends can be referenced as "module://...".
orientation{'landscape', 'portrait'}
Currently only supported by the postscript backend.
papertypestr
One of 'letter', 'legal', 'executive', 'ledger', 'a0' through 'a10', 'b0' through 'b10'. Only supported for postscript output.
transparentbool
If True, the Axes patches will all be transparent; the Figure patch will also be transparent unless facecolor and/or edgecolor are specified via kwargs. If False has no effect and the color of the Axes and Figure patches are unchanged (unless the Figure patch is specified via the facecolor and/or edgecolor keyword arguments in which case those colors are used). The transparency of these patches will be restored to their original values upon exit of this function. This is useful, for example, for displaying a plot on top of a colored background on a web page.
bbox_extra_artistslist of Artist, optional
A list of extra artists that will be considered when the tight bbox is calculated.
pil_kwargsdict, optional
Additional keyword arguments that are passed to PIL.Image.Image.save when saving the figure.
Examples using matplotlib.pyplot.savefig
Print Stdout
Rasterization for vector graphics
SVG Filter Line
SVG Filter Pie
SVG Histogram
SVG Tooltip
|
matplotlib._as_gen.matplotlib.pyplot.savefig
|
matplotlib.pyplot.sca matplotlib.pyplot.sca(ax)[source]
Set the current Axes to ax and the current Figure to the parent of ax.
|
matplotlib._as_gen.matplotlib.pyplot.sca
|
matplotlib.pyplot.scatter matplotlib.pyplot.scatter(x, y, s=None, c=None, marker=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, *, edgecolors=None, plotnonfinite=False, data=None, **kwargs)[source]
A scatter plot of y vs. x with varying marker size and/or color. Parameters
x, yfloat or array-like, shape (n, )
The data positions.
sfloat or array-like, shape (n, ), optional
The marker size in points**2. Default is rcParams['lines.markersize'] ** 2.
carray-like or list of colors or color, optional
The marker colors. Possible values: A scalar or sequence of n numbers to be mapped to colors using cmap and norm. A 2D array in which the rows are RGB or RGBA. A sequence of colors of length n. A single color format string. Note that c should not be a single numeric RGB or RGBA sequence because that is indistinguishable from an array of values to be colormapped. If you want to specify the same RGB or RGBA value for all points, use a 2D array with a single row. Otherwise, value- matching will have precedence in case of a size matching with x and y. If you wish to specify a single color for all points prefer the color keyword argument. Defaults to None. In that case the marker color is determined by the value of color, facecolor or facecolors. In case those are not specified or None, the marker color is determined by the next color of the Axes' current "shape and fill" color cycle. This cycle defaults to rcParams["axes.prop_cycle"] (default: cycler('color', ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf'])).
markerMarkerStyle, default: rcParams["scatter.marker"] (default: 'o')
The marker style. marker can be either an instance of the class or the text shorthand for a particular marker. See matplotlib.markers for more information about marker styles.
cmapstr or Colormap, default: rcParams["image.cmap"] (default: 'viridis')
A Colormap instance or registered colormap name. cmap is only used if c is an array of floats.
normNormalize, default: None
If c is an array of floats, norm is used to scale the color data, c, in the range 0 to 1, in order to map into the colormap cmap. If None, use the default colors.Normalize.
vmin, vmaxfloat, default: None
vmin and vmax are used in conjunction with the default norm to map the color array c to the colormap cmap. If None, the respective min and max of the color array is used. It is an error to use vmin/vmax when norm is given.
alphafloat, default: None
The alpha blending value, between 0 (transparent) and 1 (opaque).
linewidthsfloat or array-like, default: rcParams["lines.linewidth"] (default: 1.5)
The linewidth of the marker edges. Note: The default edgecolors is 'face'. You may want to change this as well.
edgecolors{'face', 'none', None} or color or sequence of color, default: rcParams["scatter.edgecolors"] (default: 'face')
The edge color of the marker. Possible values: 'face': The edge color will always be the same as the face color. 'none': No patch boundary will be drawn. A color or sequence of colors. For non-filled markers, edgecolors is ignored. Instead, the color is determined like with 'face', i.e. from c, colors, or facecolors.
plotnonfinitebool, default: False
Whether to plot points with nonfinite c (i.e. inf, -inf or nan). If True the points are drawn with the bad colormap color (see Colormap.set_bad). Returns
PathCollection
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, s, linewidths, edgecolors, c, facecolor, facecolors, color
**kwargsCollection properties
See also plot
To plot scatter plots when markers are identical in size and color. Notes The plot function will be faster for scatterplots where markers don't vary in size or color. Any or all of x, y, s, and c may be masked arrays, in which case all masks will be combined and only unmasked points will be plotted. Fundamentally, scatter works with 1D arrays; x, y, s, and c may be input as N-D arrays, but within scatter they will be flattened. The exception is c, which will be flattened only if its size matches the size of x and y.
Examples using matplotlib.pyplot.scatter
Scatter Masked
Scatter Symbol
Scatter plot
Hyperlinks
Pyplot tutorial
|
matplotlib._as_gen.matplotlib.pyplot.scatter
|
matplotlib.pyplot.sci matplotlib.pyplot.sci(im)[source]
Set the current image. This image will be the target of colormap functions like viridis, and other functions such as clim. The current image is an attribute of the current Axes.
Examples using matplotlib.pyplot.sci
Line Collection
|
matplotlib._as_gen.matplotlib.pyplot.sci
|
matplotlib.pyplot.semilogx matplotlib.pyplot.semilogx(*args, **kwargs)[source]
Make a plot with log scaling on the x axis. Call signatures: semilogx([x], y, [fmt], data=None, **kwargs)
semilogx([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)
This is just a thin wrapper around plot which additionally changes the x-axis to log scaling. All of the concepts and parameters of plot can be used here as well. The additional parameters base, subs, and nonpositive control the x-axis properties. They are just forwarded to Axes.set_xscale. Parameters
basefloat, default: 10
Base of the x logarithm.
subsarray-like, optional
The location of the minor xticks. If None, reasonable locations are automatically chosen depending on the number of decades in the plot. See Axes.set_xscale for details.
nonpositive{'mask', 'clip'}, default: 'mask'
Non-positive values in x can be masked as invalid, or clipped to a very small positive number. **kwargs
All parameters supported by plot. Returns
list of Line2D
Objects representing the plotted data.
|
matplotlib._as_gen.matplotlib.pyplot.semilogx
|
matplotlib.pyplot.semilogy matplotlib.pyplot.semilogy(*args, **kwargs)[source]
Make a plot with log scaling on the y axis. Call signatures: semilogy([x], y, [fmt], data=None, **kwargs)
semilogy([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)
This is just a thin wrapper around plot which additionally changes the y-axis to log scaling. All of the concepts and parameters of plot can be used here as well. The additional parameters base, subs, and nonpositive control the y-axis properties. They are just forwarded to Axes.set_yscale. Parameters
basefloat, default: 10
Base of the y logarithm.
subsarray-like, optional
The location of the minor yticks. If None, reasonable locations are automatically chosen depending on the number of decades in the plot. See Axes.set_yscale for details.
nonpositive{'mask', 'clip'}, default: 'mask'
Non-positive values in y can be masked as invalid, or clipped to a very small positive number. **kwargs
All parameters supported by plot. Returns
list of Line2D
Objects representing the plotted data.
|
matplotlib._as_gen.matplotlib.pyplot.semilogy
|
matplotlib.pyplot.set_cmap matplotlib.pyplot.set_cmap(cmap)[source]
Set the default colormap, and applies it to the current image if any. Parameters
cmapColormap or str
A colormap instance or the name of a registered colormap. See also colormaps
matplotlib.cm.register_cmap
matplotlib.cm.get_cmap
|
matplotlib._as_gen.matplotlib.pyplot.set_cmap
|
matplotlib.pyplot.set_loglevel matplotlib.pyplot.set_loglevel(*args, **kwargs)[source]
Set Matplotlib's root logger and root logger handler level, creating the handler if it does not exist yet. Typically, one should call set_loglevel("info") or set_loglevel("debug") to get additional debugging information. Parameters
level{"notset", "debug", "info", "warning", "error", "critical"}
The log level of the handler. Notes The first time this function is called, an additional handler is attached to Matplotlib's root handler; this handler is reused every time and this function simply manipulates the logger and handler's level.
|
matplotlib._as_gen.matplotlib.pyplot.set_loglevel
|
matplotlib.pyplot.setp matplotlib.pyplot.setp(obj, *args, **kwargs)[source]
Set one or more properties on an Artist, or list allowed values. Parameters
objArtist or list of Artist
The artist(s) whose properties are being set or queried. When setting properties, all artists are affected; when querying the allowed values, only the first instance in the sequence is queried. For example, two lines can be made thicker and red with a single call: >>> x = arange(0, 1, 0.01)
>>> lines = plot(x, sin(2*pi*x), x, sin(4*pi*x))
>>> setp(lines, linewidth=2, color='r')
filefile-like, default: sys.stdout
Where setp writes its output when asked to list allowed values. >>> with open('output.log') as file:
... setp(line, file=file)
The default, None, means sys.stdout. *args, **kwargs
The properties to set. The following combinations are supported:
Set the linestyle of a line to be dashed: >>> line, = plot([1, 2, 3])
>>> setp(line, linestyle='--')
Set multiple properties at once: >>> setp(line, linewidth=2, color='r')
List allowed values for a line's linestyle: >>> setp(line, 'linestyle')
linestyle: {'-', '--', '-.', ':', '', (offset, on-off-seq), ...}
List all properties that can be set, and their allowed values: >>> setp(line)
agg_filter: a filter function, ...
[long output listing omitted]
setp also supports MATLAB style string/value pairs. For example, the following are equivalent: >>> setp(lines, 'linewidth', 2, 'color', 'r') # MATLAB style
>>> setp(lines, linewidth=2, color='r') # Python style
See also getp
Examples using matplotlib.pyplot.setp
Creating a timeline with lines, dates, and text
Contouring the solution space of optimizations
Creating annotated heatmaps
Boxplots
Pie Demo2
Labeling a pie and a donut
Patheffect Demo
Set and get properties
TickedStroke patheffect
Topographic hillshading
Evans test
The Lifecycle of a Plot
|
matplotlib._as_gen.matplotlib.pyplot.setp
|
matplotlib.pyplot.show matplotlib.pyplot.show(*, block=None)[source]
Display all open figures. Parameters
blockbool, optional
Whether to wait for all figures to be closed before returning. If True block and run the GUI main loop until all figure windows are closed. If False ensure that all figure windows are displayed and return immediately. In this case, you are responsible for ensuring that the event loop is running to have responsive figures. Defaults to True in non-interactive mode and to False in interactive mode (see pyplot.isinteractive). See also ion
Enable interactive mode, which shows / updates the figure after every plotting command, so that calling show() is not necessary. ioff
Disable interactive mode. savefig
Save the figure to an image file instead of showing it on screen. Notes Saving figures to file and showing a window at the same time If you want an image file as well as a user interface window, use pyplot.savefig before pyplot.show. At the end of (a blocking) show() the figure is closed and thus unregistered from pyplot. Calling pyplot.savefig afterwards would save a new and thus empty figure. This limitation of command order does not apply if the show is non-blocking or if you keep a reference to the figure and use Figure.savefig. Auto-show in jupyter notebooks The jupyter backends (activated via %matplotlib inline, %matplotlib notebook, or %matplotlib widget), call show() at the end of every cell by default. Thus, you usually don't have to call it explicitly there.
Examples using matplotlib.pyplot.show
Bar Label Demo
Stacked bar chart
Grouped bar chart with labels
Horizontal bar chart
Broken Barh
CapStyle
Plotting categorical variables
Plotting the coherence of two signals
CSD Demo
Curve with error band
Errorbar limit selection
Errorbar subsampling
EventCollection Demo
Eventplot Demo
Filled polygon
Fill Between and Alpha
Fill Betweenx Demo
Hatch-filled histograms
Bar chart with gradients
Hat graph
Discrete distribution as horizontal bar chart
JoinStyle
Customizing dashed line styles
Lines with a ticked patheffect
Linestyles
Marker reference
Markevery Demo
prop_cycle property markevery in rcParams
Plotting masked and NaN values
Multicolored lines
Psd Demo
Scatter Custom Symbol
Scatter Demo2
Scatter plot with histograms
Scatter Masked
Scatter plot with pie chart markers
Marker examples
Scatter Symbol
Scatter plots with a legend
Simple Plot
Using span_where
Spectrum Representations
Stackplots and streamgraphs
Stairs Demo
Stem Plot
Step Demo
Creating a timeline with lines, dates, and text
hlines and vlines
Cross- and Auto-Correlation Demo
Affine transform of an image
Wind Barbs
Barcode
Contour Corner Mask
Contour Demo
Contour Image
Contour Label Demo
Contourf Demo
Contourf Hatching
Contourf and log color scale
Contouring the solution space of optimizations
BboxImage Demo
Figimage Demo
Creating annotated heatmaps
Image antialiasing
Clipping images with patches
Image Demo
Image Masked
Image Nonuniform
Blend transparency with color in 2D images
Modifying the coordinate formatter
Interpolations for imshow
Contour plot of irregularly spaced data
Layer Images
Matshow
Multi Image
Pcolor Demo
pcolormesh grids and shading
pcolormesh
Streamplot
QuadMesh Demo
Advanced quiver and quiverkey functions
Quiver Simple Demo
Shading example
Spectrogram Demo
Spy Demos
Tricontour Demo
Tricontour Smooth Delaunay
Tricontour Smooth User
Trigradient Demo
Triinterp Demo
Tripcolor Demo
Triplot Demo
Watermark image
Aligning Labels
Axes box aspect
Axes Demo
Controlling view limits using margins and sticky_edges
Axes Props
Axes Zoom Effect
axhspan Demo
Equal axis aspect ratio
Axis Label Position
Broken Axis
Placing Colorbars
Resizing axes with constrained layout
Resizing axes with tight layout
Different scales on the same axes
Figure size in different units
Figure labels: suptitle, supxlabel, supylabel
Creating adjacent subplots
Geographic Projections
Combining two subplots using subplots and GridSpec
Using Gridspec to make multi-column/row subplot layouts
Nested Gridspecs
Invert Axes
Managing multiple figures in pyplot
Secondary Axis
Sharing axis limits and views
Shared Axis
Figure subfigures
Multiple subplots
Subplots spacings and margins
Creating multiple subplots using plt.subplots
Plots with different scales
Zoom region inset axes
Percentiles as horizontal bar chart
Artist customization in box plots
Box plots with custom fill colors
Boxplots
Box plot vs. violin plot comparison
Boxplot drawer function
Plot a confidence ellipse of a two-dimensional dataset
Violin plot customization
Errorbar function
Different ways of specifying error bars
Including upper and lower limits in error bars
Creating boxes from error bars using PatchCollection
Hexagonal binned plot
Histograms
Using histograms to plot a cumulative distribution
Some features of the histogram (hist) function
Demo of the histogram function's different histtype settings
The histogram (hist) function with multiple data sets
Producing multiple histograms side by side
Time Series Histogram
Violin plot basics
Basic pie chart
Pie Demo2
Bar of pie
Nested pie charts
Labeling a pie and a donut
Bar chart on polar axis
Polar plot
Polar Legend
Scatter plot on polar axis
Using accented text in matplotlib
Scale invariant angle label
Annotating Plots
Arrow Demo
Auto-wrapping text
Composing Custom Legends
Date tick labels
Custom tick formatter for time series
AnnotationBbox demo
Using a text as a Path
Text Rotation Mode
The difference between \dfrac and \frac
Labeling ticks using engineering notation
Annotation arrow style reference
Styling text boxes
Figure legend demo
Configuring the font family
Using a ttf font file in Matplotlib
Font table
Fonts demo (object-oriented style)
Fonts demo (keyword arguments)
Labelling subplots
Legend using pre-defined labels
Legend Demo
Artist within an artist
Convert texts to images
Mathtext
Mathtext Examples
Math fontfamily
Multiline
Placing text boxes
Rainbow text
STIX Fonts
Rendering math equations using TeX
Precise text layout
Controlling style of text and labels using a dictionary
Default text rotation demonstration
Text Rotation Relative To Line
Title positioning
Unicode minus
Usetex Baseline Test
Usetex Fonteffects
Text watermark
Align y-labels
Annotate Transform
Annotating a plot
Annotation Polar
Programmatically controlling subplot adjustment
Infinite lines
Boxplot Demo
Dollar Ticks
Fig Axes Customize Simple
Simple axes labels
Adding lines to figures
plot() format string
Pyplot Mathtext
Pyplot Simple
Pyplot Text
Pyplot Three
Pyplot Two Subplots
Text Commands
Text Layout
Color Demo
Color by y-value
Colors in the default property cycle
Colorbar
Colormap reference
Creating a colormap from a list of colors
List of named colors
Arrow guide
Reference for Matplotlib artists
Line, Poly and RegularPoly Collection with autoscaling
Compound path
Dolphins
Mmh Donuts!!!
Ellipse Collection
Ellipse Demo
Drawing fancy boxes
Hatch demo
Line Collection
Circles, Wedges and Polygons
PathPatch object
Bezier Curve
Scatter plot
Bayesian Methods for Hackers style sheet
Dark background style sheet
FiveThirtyEight style sheet
ggplot style sheet
Grayscale style sheet
Solarized Light stylesheet
Style sheets reference
Anchored Direction Arrow
Axes Divider
Demo Axes Grid
Axes Grid2
HBoxDivider demo
Showing RGB channels using RGBAxes
Adding a colorbar to inset axes
Colorbar with AxesDivider
Controlling the position and size of colorbars with Inset Axes
Per-row or per-column colorbars
Axes with a fixed physical size
Setting a fixed aspect on ImageGrid cells
Inset Locator Demo
Inset Locator Demo2
Make Room For Ylabel Using Axesgrid
Parasite Simple
Parasite Simple2
Scatter Histogram (Locatable Axes)
Simple Anchored Artists
Simple Axes Divider 1
Simple Axes Divider 3
Simple ImageGrid
Simple ImageGrid 2
Simple Axisline4
Simple Colorbar
Axis Direction
axis_direction demo
Axis line styles
Curvilinear grid demo
Demo CurveLinear Grid2
mpl_toolkits.axisartist.floating_axes features
floating_axis demo
Parasite Axes demo
Parasite axis demo
Ticklabel alignment
Ticklabel direction
Simple Axis Direction01
Simple Axis Direction03
Simple Axis Pad
Custom spines with axisartist
Simple Axisline
Simple Axisline3
Anatomy of a figure
Bachelor's degrees by gender
Firefox
Integral as the area under a curve
Shaded & power normalized rendering
XKCD
Decay
Animated histogram
The Bayes update
The double pendulum problem
Animated image using a precomputed list of images
Pausing and Resuming an Animation
Rain simulation
Animated 3D random walk
Animated line plot
Oscilloscope
MATPLOTLIB UNCHAINED
Close Event
Mouse move and click events
Data Browser
Figure/Axes enter and leave events
Interactive functions
Image Slices Viewer
Keypress event
Lasso Demo
Legend Picking
Looking Glass
Path Editor
Pick Event Demo
Pick Event Demo2
Poly Editor
Pong
Resampling Data
Timers
Trifinder Event Demo
Viewlims
Zoom Window
Frontpage contour example
Anchored Artists
Changing colors of lines intersecting a box
Manual Contour
Coords Report
Cross hair cursor
Custom projection
Customize Rc
AGG filter
Ribbon Box
Fill Spiral
Findobj Demo
Building histograms using Rectangles and PolyCollections
Plotting with keywords
Matplotlib logo
Multiprocess
Packed-bubble chart
Patheffect Demo
Pythonic Matplotlib
Set and get properties
Table Demo
TickedStroke patheffect
transforms.offset_copy
Zorder Demo
Plot 2D data on 3D plot
Demo of 3D bar charts
Create 2D bar graphs in different planes
3D box surface plot
Demonstrates plotting contour (level) curves in 3D
Demonstrates plotting contour (level) curves in 3D using the extend3d option
Projecting contour profiles onto a graph
Filled contours
Projecting filled contour onto a graph
Custom hillshading in a 3D surface plot
3D errorbars
Create 3D histogram of 2D data
Parametric Curve
Lorenz Attractor
2D and 3D Axes in same Figure
Automatic Text Offsetting
Draw flat objects in 3D plot
Generate polygons to fill under 3D line graph
3D quiver plot
3D scatterplot
3D stem
3D plots as subplots
3D surface (colormap)
3D surface (solid color)
3D surface (checkerboard)
3D surface with polar coordinates
Text annotations in 3D
Triangular 3D contour plot
Triangular 3D filled contour plot
Triangular 3D surfaces
More triangular 3D surfaces
3D voxel / volumetric plot
3D voxel plot of the numpy logo
3D voxel / volumetric plot with rgb colors
3D voxel / volumetric plot with cylindrical coordinates
3D wireframe plot
3D wireframe plots in one direction
Loglog Aspect
Custom scale
Log Bar
Log Demo
Log Axis
Logit Demo
Exploring normalizations
Scales
Symlog Demo
Hillshading
Anscombe's quartet
Hinton diagrams
Left ventricle bullseye
MRI
MRI With EEG
Radar chart (aka spider or star chart)
The Sankey class
Long chain of connections using Sankey
Rankine power cycle
SkewT-logP diagram: using transforms and custom projections
Topographic hillshading
Centered spines with arrows
Multiple Yaxis With Spines
Spine Placement
Spines
Custom spine bounds
Dropped spines
Automatically setting tick positions
Centering labels between ticks
Colorbar Tick Labelling
Custom Ticker1
Formatting date ticks using ConciseDateFormatter
Date Demo Convert
Placing date ticks using recurrence rules
Date Index Formatter
Date Precision and Epochs
Major and minor ticks
The default tick formatter
Tick formatters
Tick locators
Set default y-axis tick labels on the right
Setting tick labels from a list of values
Set default x-axis tick labels on the top
Rotating custom tick labels
Annotation with units
Artist tests
Bar demo with units
Group barchart with units
Ellipse With Units
Evans test
Radian ticks
Inches and Centimeters
Unit handling
pyplot with GTK3
pyplot with GTK4
Tool Manager
Anchored Box04
Annotate Explain
Annotate Simple01
Annotate Simple02
Annotate Simple03
Annotate Simple04
Annotate Simple Coord01
Annotate Simple Coord02
Annotate Simple Coord03
Annotate Text Arrow
Interactive Adjustment of Colormap Range
Colormap Normalizations
Colormap Normalizations Symlognorm
Connect Simple01
Connection styles for annotations
Custom box styles
subplot2grid demo
GridSpec demo
Nested GridSpecs
Simple Annotate01
Simple Legend01
Simple Legend02
Annotated Cursor
Buttons
Check Buttons
Cursor
Lasso Selector
Menu
Mouse Cursor
Multicursor
Polygon Selector
Radio Buttons
Thresholding an Image with RangeSlider
Rectangle and ellipse selectors
Slider
Snapping Sliders to Discrete Values
Span Selector
Textbox
Pyplot tutorial
The Lifecycle of a Plot
Customizing Matplotlib with style sheets and rcParams
Artist tutorial
Legend guide
Styling with cycler
Constrained Layout Guide
Tight Layout guide
Arranging multiple Axes in a Figure
origin and extent in imshow
Faster rendering by using blitting
Path Tutorial
Path effects guide
Transformations Tutorial
Specifying Colors
Customized Colorbars Tutorial
Creating Colormaps in Matplotlib
Colormap Normalization
Choosing Colormaps in Matplotlib
Text in Matplotlib Plots
Text properties and layout
plot(x, y)
scatter(x, y)
bar(x, height) / barh(y, width)
stem(x, y)
step(x, y)
fill_between(x, y1, y2)
imshow(Z)
pcolormesh(X, Y, Z)
contour(X, Y, Z)
contourf(X, Y, Z)
barbs(X, Y, U, V)
quiver(X, Y, U, V)
streamplot(X, Y, U, V)
hist(x)
boxplot(X)
errorbar(x, y, yerr, xerr)
violinplot(D)
eventplot(D)
hist2d(x, y)
hexbin(x, y, C)
pie(x)
tricontour(x, y, z)
tricontourf(x, y, z)
tripcolor(x, y, z)
triplot(x, y)
|
matplotlib._as_gen.matplotlib.pyplot.show
|
matplotlib.pyplot.specgram matplotlib.pyplot.specgram(x, NFFT=None, Fs=None, Fc=None, detrend=None, window=None, noverlap=None, cmap=None, xextent=None, pad_to=None, sides=None, scale_by_freq=None, mode=None, scale=None, vmin=None, vmax=None, *, data=None, **kwargs)[source]
Plot a spectrogram. Compute and plot a spectrogram of data in x. Data are split into NFFT length segments and the spectrum of each section is computed. The windowing function window is applied to each segment, and the amount of overlap of each segment is specified with noverlap. The spectrogram is plotted as a colormap (using imshow). Parameters
x1-D array or sequence
Array or sequence 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.
mode{'default', 'psd', 'magnitude', 'angle', 'phase'}
What sort of spectrum to use. Default is 'psd', which takes the power spectral density. 'magnitude' returns the magnitude spectrum. 'angle' returns the phase spectrum without unwrapping. 'phase' returns the phase spectrum with unwrapping.
noverlapint, default: 128
The number of points of overlap between blocks.
scale{'default', 'linear', 'dB'}
The scaling of the values in the spec. 'linear' is no scaling. 'dB' returns the values in dB scale. When mode is 'psd', this is dB power (10 * log10). Otherwise this is dB amplitude (20 * log10). 'default' is 'dB' if mode is 'psd' or 'magnitude' and 'linear' otherwise. This must be 'linear' if mode is 'angle' or 'phase'.
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.
cmapColormap, default: rcParams["image.cmap"] (default: 'viridis')
xextentNone or (xmin, xmax)
The image extent along the x-axis. The default sets xmin to the left border of the first bin (spectrum column) and xmax to the right border of the last bin. Note that for noverlap>0 the width of the bins is smaller than those of the segments.
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 **kwargs
Additional keyword arguments are passed on to imshow which makes the specgram image. The origin keyword argument is not supported. Returns
spectrum2D array
Columns are the periodograms of successive segments.
freqs1-D array
The frequencies corresponding to the rows in spectrum.
t1-D array
The times corresponding to midpoints of segments (i.e., the columns in spectrum).
imAxesImage
The image created by imshow containing the spectrogram. See also psd
Differs in the default overlap; in returning the mean of the segment periodograms; in not returning times; and in generating a line plot instead of colormap. magnitude_spectrum
A single spectrum, similar to having a single segment when mode is 'magnitude'. Plots a line instead of a colormap. angle_spectrum
A single spectrum, similar to having a single segment when mode is 'angle'. Plots a line instead of a colormap. phase_spectrum
A single spectrum, similar to having a single segment when mode is 'phase'. Plots a line instead of a colormap. Notes The parameters detrend and scale_by_freq do only apply when mode is set to 'psd'.
|
matplotlib._as_gen.matplotlib.pyplot.specgram
|
matplotlib.pyplot.spring matplotlib.pyplot.spring()[source]
Set the colormap to 'spring'. This changes the default colormap as well as the colormap of the current image if there is one. See help(colormaps) for more information.
|
matplotlib._as_gen.matplotlib.pyplot.spring
|
matplotlib.pyplot.spy matplotlib.pyplot.spy(Z, precision=0, marker=None, markersize=None, aspect='equal', origin='upper', **kwargs)[source]
Plot the sparsity pattern of a 2D array. This visualizes the non-zero values of the array. Two plotting styles are available: image and marker. Both are available for full arrays, but only the marker style works for scipy.sparse.spmatrix instances. Image style If marker and markersize are None, imshow is used. Any extra remaining keyword arguments are passed to this method. Marker style If Z is a scipy.sparse.spmatrix or marker or markersize are None, a Line2D object will be returned with the value of marker determining the marker type, and any remaining keyword arguments passed to plot. Parameters
Z(M, N) array-like
The array to be plotted.
precisionfloat or 'present', default: 0
If precision is 0, any non-zero value will be plotted. Otherwise, values of \(|Z| > precision\) will be plotted. For scipy.sparse.spmatrix instances, you can also pass 'present'. In this case any value present in the array will be plotted, even if it is identically zero.
aspect{'equal', 'auto', None} or float, default: 'equal'
The aspect ratio of the Axes. This parameter is particularly relevant for images since it determines whether data pixels are square. This parameter is a shortcut for explicitly calling Axes.set_aspect. See there for further details. 'equal': Ensures an aspect ratio of 1. Pixels will be square. 'auto': The Axes is kept fixed and the aspect is adjusted so that the data fit in the Axes. In general, this will result in non-square pixels.
None: Use rcParams["image.aspect"] (default: 'equal').
origin{'upper', 'lower'}, default: rcParams["image.origin"] (default: 'upper')
Place the [0, 0] index of the array in the upper left or lower left corner of the Axes. The convention 'upper' is typically used for matrices and images. Returns
AxesImage or Line2D
The return type depends on the plotting style (see above). Other Parameters
**kwargs
The supported additional parameters depend on the plotting style. For the image style, you can pass the following additional parameters of imshow: cmap alpha url any Artist properties (passed on to the AxesImage) For the marker style, you can pass any Line2D property except for linestyle:
Property Description
agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha scalar or None
animated bool
antialiased or aa bool
clip_box Bbox
clip_on bool
clip_path Patch or (Path, Transform) or None
color or c color
dash_capstyle CapStyle or {'butt', 'projecting', 'round'}
dash_joinstyle JoinStyle or {'miter', 'round', 'bevel'}
dashes sequence of floats (on/off ink in points) or (None, None)
data (2, N) array or two 1D arrays
drawstyle or ds {'default', 'steps', 'steps-pre', 'steps-mid', 'steps-post'}, default: 'default'
figure Figure
fillstyle {'full', 'left', 'right', 'bottom', 'top', 'none'}
gid str
in_layout bool
label object
linestyle or ls {'-', '--', '-.', ':', '', (offset, on-off-seq), ...}
linewidth or lw float
marker marker style string, Path or MarkerStyle
markeredgecolor or mec color
markeredgewidth or mew float
markerfacecolor or mfc color
markerfacecoloralt or mfcalt color
markersize or ms float
markevery None or int or (int, int) or slice or list[int] or float or (float, float) or list[bool]
path_effects AbstractPathEffect
picker float or callable[[Artist, Event], tuple[bool, dict]]
pickradius float
rasterized bool
sketch_params (scale: float, length: float, randomness: float)
snap bool or None
solid_capstyle CapStyle or {'butt', 'projecting', 'round'}
solid_joinstyle JoinStyle or {'miter', 'round', 'bevel'}
transform unknown
url str
visible bool
xdata 1D array
ydata 1D array
zorder float
|
matplotlib._as_gen.matplotlib.pyplot.spy
|
matplotlib.pyplot.stackplot matplotlib.pyplot.stackplot(x, *args, labels=(), colors=None, baseline='zero', data=None, **kwargs)[source]
Draw a stacked area plot. Parameters
x(N,) array-like
y(M, N) array-like
The data is assumed to be unstacked. Each of the following calls is legal: stackplot(x, y) # where y has shape (M, N)
stackplot(x, y1, y2, y3) # where y1, y2, y3, y4 have length N
baseline{'zero', 'sym', 'wiggle', 'weighted_wiggle'}
Method used to calculate the baseline:
'zero': Constant zero baseline, i.e. a simple stacked plot.
'sym': Symmetric around zero and is sometimes called 'ThemeRiver'.
'wiggle': Minimizes the sum of the squared slopes.
'weighted_wiggle': Does the same but weights to account for size of each layer. It is also called 'Streamgraph'-layout. More details can be found at http://leebyron.com/streamgraph/.
labelslist of str, optional
A sequence of labels to assign to each data series. If unspecified, then no labels will be applied to artists.
colorslist of color, optional
A sequence of colors to be cycled through and used to color the stacked areas. The sequence need not be exactly the same length as the number of provided y, in which case the colors will repeat from the beginning. If not specified, the colors from the Axes property cycle will be used.
dataindexable object, optional
If given, all parameters also accept a string s, which is interpreted as data[s] (unless this raises an exception). **kwargs
All other keyword arguments are passed to Axes.fill_between. Returns
list of PolyCollection
A list of PolyCollection instances, one for each element in the stacked area plot.
|
matplotlib._as_gen.matplotlib.pyplot.stackplot
|
matplotlib.pyplot.stairs matplotlib.pyplot.stairs(values, edges=None, *, orientation='vertical', baseline=0, fill=False, data=None, **kwargs)[source]
A stepwise constant function as a line with bounding edges or a filled plot. Parameters
valuesarray-like
The step heights.
edgesarray-like
The edge positions, with len(edges) == len(vals) + 1, between which the curve takes on vals values.
orientation{'vertical', 'horizontal'}, default: 'vertical'
The direction of the steps. Vertical means that values are along the y-axis, and edges are along the x-axis.
baselinefloat, array-like or None, default: 0
The bottom value of the bounding edges or when fill=True, position of lower edge. If fill is True or an array is passed to baseline, a closed path is drawn.
fillbool, default: False
Whether the area under the step curve should be filled. Returns
StepPatchmatplotlib.patches.StepPatch
Other Parameters
dataindexable object, optional
If given, all parameters also accept a string s, which is interpreted as data[s] (unless this raises an exception). **kwargs
StepPatch properties
Examples using matplotlib.pyplot.stairs
Stairs Demo
|
matplotlib._as_gen.matplotlib.pyplot.stairs
|
matplotlib.pyplot.stem matplotlib.pyplot.stem(*args, linefmt=None, markerfmt=None, basefmt=None, bottom=0, label=None, use_line_collection=True, orientation='vertical', data=None)[source]
Create a stem plot. A stem plot draws lines perpendicular to a baseline at each location locs from the baseline to heads, and places a marker there. For vertical stem plots (the default), the locs are x positions, and the heads are y values. For horizontal stem plots, the locs are y positions, and the heads are x values. Call signature: stem([locs,] heads, linefmt=None, markerfmt=None, basefmt=None)
The locs-positions are optional. The formats may be provided either as positional or as keyword-arguments. Parameters
locsarray-like, default: (0, 1, ..., len(heads) - 1)
For vertical stem plots, the x-positions of the stems. For horizontal stem plots, the y-positions of the stems.
headsarray-like
For vertical stem plots, the y-values of the stem heads. For horizontal stem plots, the x-values of the stem heads.
linefmtstr, optional
A string defining the color and/or linestyle of the vertical lines:
Character Line Style
'-' solid line
'--' dashed line
'-.' dash-dot line
':' dotted line Default: 'C0-', i.e. solid line with the first color of the color cycle. Note: Markers specified through this parameter (e.g. 'x') will be silently ignored (unless using use_line_collection=False). Instead, markers should be specified using markerfmt.
markerfmtstr, optional
A string defining the color and/or shape of the markers at the stem heads. Default: 'C0o', i.e. filled circles with the first color of the color cycle.
basefmtstr, default: 'C3-' ('C2-' in classic mode)
A format string defining the properties of the baseline.
orientationstr, default: 'vertical'
If 'vertical', will produce a plot with stems oriented vertically, otherwise the stems will be oriented horizontally.
bottomfloat, default: 0
The y/x-position of the baseline (depending on orientation).
labelstr, default: None
The label to use for the stems in legends.
use_line_collectionbool, default: True
If True, store and plot the stem lines as a LineCollection instead of individual lines, which significantly increases performance. If False, defaults to the old behavior of using a list of Line2D objects. This parameter may be deprecated in the future.
dataindexable object, optional
If given, all parameters also accept a string s, which is interpreted as data[s] (unless this raises an exception). Returns
StemContainer
The container may be treated like a tuple (markerline, stemlines, baseline) Notes See also The MATLAB function stem which inspired this method.
Examples using matplotlib.pyplot.stem
Stem Plot
|
matplotlib._as_gen.matplotlib.pyplot.stem
|
matplotlib.pyplot.step matplotlib.pyplot.step(x, y, *args, where='pre', data=None, **kwargs)[source]
Make a step plot. Call signatures: step(x, y, [fmt], *, data=None, where='pre', **kwargs)
step(x, y, [fmt], x2, y2, [fmt2], ..., *, where='pre', **kwargs)
This is just a thin wrapper around plot which changes some formatting options. Most of the concepts and parameters of plot can be used here as well. Note This method uses a standard plot with a step drawstyle: The x values are the reference positions and steps extend left/right/both directions depending on where. For the common case where you know the values and edges of the steps, use stairs instead. Parameters
xarray-like
1D sequence of x positions. It is assumed, but not checked, that it is uniformly increasing.
yarray-like
1D sequence of y levels.
fmtstr, optional
A format string, e.g. 'g' for a green line. See plot for a more detailed description. Note: While full format strings are accepted, it is recommended to only specify the color. Line styles are currently ignored (use the keyword argument linestyle instead). Markers are accepted and plotted on the given positions, however, this is a rarely needed feature for step plots.
where{'pre', 'post', 'mid'}, default: 'pre'
Define where the steps should be placed: 'pre': The y value is continued constantly to the left from every x position, i.e. the interval (x[i-1], x[i]] has the 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.
dataindexable object, optional
An object with labelled data. If given, provide the label names to plot in x and y. **kwargs
Additional parameters are the same as those for plot. Returns
list of Line2D
Objects representing the plotted data.
Examples using matplotlib.pyplot.step
Stairs Demo
Step Demo
|
matplotlib._as_gen.matplotlib.pyplot.step
|
matplotlib.pyplot.streamplot matplotlib.pyplot.streamplot(x, y, u, v, density=1, linewidth=None, color=None, cmap=None, norm=None, arrowsize=1, arrowstyle='-|>', minlength=0.1, transform=None, zorder=None, start_points=None, maxlength=4.0, integration_direction='both', *, data=None)[source]
Draw streamlines of a vector flow. Parameters
x, y1D/2D arrays
Evenly spaced strictly increasing arrays to make a grid. If 2D, all rows of x must be equal and all columns of y must be equal; i.e., they must be as if generated by np.meshgrid(x_1d, y_1d).
u, v2D arrays
x and y-velocities. The number of rows and columns must match the length of y and x, respectively.
densityfloat or (float, float)
Controls the closeness of streamlines. When density = 1, the domain is divided into a 30x30 grid. density linearly scales this grid. Each cell in the grid can have, at most, one traversing streamline. For different densities in each direction, use a tuple (density_x, density_y).
linewidthfloat or 2D array
The width of the stream lines. With a 2D array the line width can be varied across the grid. The array must have the same shape as u and v.
colorcolor or 2D array
The streamline color. If given an array, its values are converted to colors using cmap and norm. The array must have the same shape as u and v.
cmapColormap
Colormap used to plot streamlines and arrows. This is only used if color is an array.
normNormalize
Normalize object used to scale luminance data to 0, 1. If None, stretch (min, max) to (0, 1). This is only used if color is an array.
arrowsizefloat
Scaling factor for the arrow size.
arrowstylestr
Arrow style specification. See FancyArrowPatch.
minlengthfloat
Minimum length of streamline in axes coordinates.
start_pointsNx2 array
Coordinates of starting points for the streamlines in data coordinates (the same coordinates as the x and y arrays).
zorderint
The zorder of the stream lines and arrows. Artists with lower zorder values are drawn first.
maxlengthfloat
Maximum length of streamline in axes coordinates.
integration_direction{'forward', 'backward', 'both'}, default: 'both'
Integrate the streamline in forward, backward or both directions.
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, u, v, start_points Returns
StreamplotSet
Container object with attributes
lines: LineCollection of streamlines
arrows: PatchCollection containing FancyArrowPatch objects representing the arrows half-way along stream lines. This container will probably change in the future to allow changes to the colormap, alpha, etc. for both lines and arrows, but these changes should be backward compatible.
|
matplotlib._as_gen.matplotlib.pyplot.streamplot
|
matplotlib.pyplot.subplot matplotlib.pyplot.subplot(*args, **kwargs)[source]
Add an Axes to the current figure or retrieve an existing Axes. This is a wrapper of Figure.add_subplot which provides additional behavior when working with the implicit API (see the notes section). Call signatures: subplot(nrows, ncols, index, **kwargs)
subplot(pos, **kwargs)
subplot(**kwargs)
subplot(ax)
Parameters
*argsint, (int, int, index), or SubplotSpec, default: (1, 1, 1)
The position of the subplot described by one of Three integers (nrows, ncols, index). The subplot will take the index position on a grid with nrows rows and ncols columns. index starts at 1 in the upper left corner and increases to the right. index can also be a two-tuple specifying the (first, last) indices (1-based, and including last) of the subplot, e.g., fig.add_subplot(3, 1, (1, 2)) makes a subplot that spans the upper 2/3 of the figure. A 3-digit integer. The digits are interpreted as if given separately as three single-digit integers, i.e. fig.add_subplot(235) is the same as fig.add_subplot(2, 3, 5). Note that this can only be used if there are no more than 9 subplots. A SubplotSpec.
projection{None, 'aitoff', 'hammer', 'lambert', 'mollweide', 'polar', 'rectilinear', str}, optional
The projection type of the subplot (Axes). str is the name of a custom projection, see projections. The default None results in a 'rectilinear' projection.
polarbool, default: False
If True, equivalent to projection='polar'.
sharex, shareyAxes, optional
Share the x or y axis with sharex and/or sharey. The axis will have the same limits, ticks, and scale as the axis of the shared axes.
labelstr
A label for the returned axes. Returns
axes.SubplotBase, or another subclass of Axes
The axes of the subplot. The returned axes base class depends on the projection used. It is Axes if rectilinear projection is used and projections.polar.PolarAxes if polar projection is used. The returned axes is then a subplot subclass of the base class. Other Parameters
**kwargs
This method also takes the keyword arguments for the returned axes base class; except for the figure argument. The keyword arguments for the rectilinear base class Axes can be found in the following table but there might also be other keyword arguments if another projection is used.
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 See also Figure.add_subplot
pyplot.subplots
pyplot.axes
Figure.subplots
Notes Creating a new Axes will delete any pre-existing Axes that overlaps with it beyond sharing a boundary: import matplotlib.pyplot as plt
# plot a line, implicitly creating a subplot(111)
plt.plot([1, 2, 3])
# now create a subplot which represents the top plot of a grid
# with 2 rows and 1 column. Since this subplot will overlap the
# first, the plot (and its axes) previously created, will be removed
plt.subplot(211)
If you do not want this behavior, use the Figure.add_subplot method or the pyplot.axes function instead. If no kwargs are passed and there exists an Axes in the location specified by args then that Axes will be returned rather than a new Axes being created. If kwargs are passed and there exists an Axes in the location specified by args, the projection type is the same, and the kwargs match with the existing Axes, then the existing Axes is returned. Otherwise a new Axes is created with the specified parameters. We save a reference to the kwargs which we use for this comparison. If any of the values in kwargs are mutable we will not detect the case where they are mutated. In these cases we suggest using Figure.add_subplot and the explicit Axes API rather than the implicit pyplot API. Examples plt.subplot(221)
# equivalent but more general
ax1 = plt.subplot(2, 2, 1)
# add a subplot with no frame
ax2 = plt.subplot(222, frameon=False)
# add a polar subplot
plt.subplot(223, projection='polar')
# add a red subplot that shares the x-axis with ax1
plt.subplot(224, sharex=ax1, facecolor='red')
# delete ax2 from the figure
plt.delaxes(ax2)
# add ax2 to the figure again
plt.subplot(ax2)
# make the first axes "current" again
plt.subplot(221)
Examples using matplotlib.pyplot.subplot
Controlling view limits using margins and sticky_edges
Resizing axes with tight layout
Geographic Projections
Managing multiple figures in pyplot
Sharing axis limits and views
Shared Axis
Multiple subplots
Subplots spacings and margins
Bar chart on polar axis
Pyplot Two Subplots
Simple Colorbar
MATPLOTLIB UNCHAINED
Customize Rc
transforms.offset_copy
Pyplot tutorial
Constrained Layout Guide
Tight Layout guide
|
matplotlib._as_gen.matplotlib.pyplot.subplot
|
matplotlib.pyplot.subplot2grid matplotlib.pyplot.subplot2grid(shape, loc, rowspan=1, colspan=1, fig=None, **kwargs)[source]
Create a subplot at a specific location inside a regular grid. Parameters
shape(int, int)
Number of rows and of columns of the grid in which to place axis.
loc(int, int)
Row number and column number of the axis location within the grid.
rowspanint, default: 1
Number of rows for the axis to span downwards.
colspanint, default: 1
Number of columns for the axis to span to the right.
figFigure, optional
Figure to place the subplot in. Defaults to the current figure. **kwargs
Additional keyword arguments are handed to add_subplot. Returns
axes.SubplotBase, or another subclass of Axes
The axes of the subplot. The returned axes base class depends on the projection used. It is Axes if rectilinear projection is used and projections.polar.PolarAxes if polar projection is used. The returned axes is then a subplot subclass of the base class. Notes The following call ax = subplot2grid((nrows, ncols), (row, col), rowspan, colspan)
is identical to fig = gcf()
gs = fig.add_gridspec(nrows, ncols)
ax = fig.add_subplot(gs[row:row+rowspan, col:col+colspan])
Examples using matplotlib.pyplot.subplot2grid
Resizing axes with tight layout
subplot2grid demo
Constrained Layout Guide
Tight Layout guide
|
matplotlib._as_gen.matplotlib.pyplot.subplot2grid
|
matplotlib.pyplot.subplot_mosaic matplotlib.pyplot.subplot_mosaic(mosaic, *, sharex=False, sharey=False, subplot_kw=None, gridspec_kw=None, empty_sentinel='.', **fig_kw)[source]
Build a layout of Axes based on ASCII art or nested lists. This is a helper function to build complex GridSpec layouts visually. Note This API is provisional and may be revised in the future based on early user feedback. Parameters
mosaiclist of list of {hashable or nested} or str
A visual layout of how you want your Axes to be arranged labeled as strings. For example x = [['A panel', 'A panel', 'edge'],
['C panel', '.', 'edge']]
produces 4 axes: 'A panel' which is 1 row high and spans the first two columns 'edge' which is 2 rows high and is on the right edge 'C panel' which in 1 row and 1 column wide in the bottom left a blank space 1 row and 1 column wide in the bottom center Any of the entries in the layout can be a list of lists of the same form to create nested layouts. If input is a str, then it must be of the form '''
AAE
C.E
'''
where each character is a column and each line is a row. This only allows only single character Axes labels and does not allow nesting but is very terse.
sharex, shareybool, default: False
If True, the x-axis (sharex) or y-axis (sharey) will be shared among all subplots. In that case, tick label visibility and axis units behave as for subplots. If False, each subplot's x- or y-axis will be independent.
subplot_kwdict, optional
Dictionary with keywords passed to the Figure.add_subplot call used to create each subplot.
gridspec_kwdict, optional
Dictionary with keywords passed to the GridSpec constructor used to create the grid the subplots are placed on.
empty_sentinelobject, optional
Entry in the layout to mean "leave this space empty". Defaults to '.'. Note, if layout is a string, it is processed via inspect.cleandoc to remove leading white space, which may interfere with using white-space as the empty sentinel. **fig_kw
All additional keyword arguments are passed to the pyplot.figure call. Returns
figFigure
The new figure dict[label, Axes]
A dictionary mapping the labels to the Axes objects. The order of the axes is left-to-right and top-to-bottom of their position in the total layout.
Examples using matplotlib.pyplot.subplot_mosaic
Image Demo
Labelling subplots
Basic Usage
Legend guide
Arranging multiple Axes in a Figure
|
matplotlib._as_gen.matplotlib.pyplot.subplot_mosaic
|
matplotlib.pyplot.subplot_tool matplotlib.pyplot.subplot_tool(targetfig=None)[source]
Launch a subplot tool window for a figure. Returns
matplotlib.widgets.SubplotTool
|
matplotlib._as_gen.matplotlib.pyplot.subplot_tool
|
matplotlib.pyplot.subplots matplotlib.pyplot.subplots(nrows=1, ncols=1, *, sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None, **fig_kw)[source]
Create a figure and a set of subplots. This utility wrapper makes it convenient to create common layouts of subplots, including the enclosing figure object, in a single call. Parameters
nrows, ncolsint, default: 1
Number of rows/columns of the subplot grid.
sharex, shareybool or {'none', 'all', 'row', 'col'}, default: False
Controls sharing of properties among x (sharex) or y (sharey) axes: True or 'all': x- or y-axis will be shared among all subplots. False or 'none': each subplot x- or y-axis will be independent. 'row': each subplot row will share an x- or y-axis. 'col': each subplot column will share an x- or y-axis. When subplots have a shared x-axis along a column, only the x tick labels of the bottom subplot are created. Similarly, when subplots have a shared y-axis along a row, only the y tick labels of the first column subplot are created. To later turn other subplots' ticklabels on, use tick_params. When subplots have a shared axis that has units, calling set_units will update each axis with the new units.
squeezebool, default: True
If True, extra dimensions are squeezed out from the returned array of Axes: if only one subplot is constructed (nrows=ncols=1), the resulting single Axes object is returned as a scalar. for Nx1 or 1xM subplots, the returned object is a 1D numpy object array of Axes objects. for NxM, subplots with N>1 and M>1 are returned as a 2D array. If False, no squeezing at all is done: the returned Axes object is always a 2D array containing Axes instances, even if it ends up being 1x1.
subplot_kwdict, optional
Dict with keywords passed to the add_subplot call used to create each subplot.
gridspec_kwdict, optional
Dict with keywords passed to the GridSpec constructor used to create the grid the subplots are placed on. **fig_kw
All additional keyword arguments are passed to the pyplot.figure call. Returns
figFigure
axaxes.Axes or array of Axes
ax can be either a single Axes object or an array of Axes objects if more than one subplot was created. The dimensions of the resulting array can be controlled with the squeeze keyword, see above. Typical idioms for handling the return value are: # using the variable ax for single a Axes
fig, ax = plt.subplots()
# using the variable axs for multiple Axes
fig, axs = plt.subplots(2, 2)
# using tuple unpacking for multiple Axes
fig, (ax1, ax2) = plt.subplots(1, 2)
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)
The names ax and pluralized axs are preferred over axes because for the latter it's not clear if it refers to a single Axes instance or a collection of these. See also pyplot.figure
pyplot.subplot
pyplot.axes
Figure.subplots
Figure.add_subplot
Examples # First create some toy data:
x = np.linspace(0, 2*np.pi, 400)
y = np.sin(x**2)
# Create just a figure and only one subplot
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_title('Simple plot')
# Create two subplots and unpack the output array immediately
f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
ax1.plot(x, y)
ax1.set_title('Sharing Y axis')
ax2.scatter(x, y)
# Create four polar axes and access them through the returned array
fig, axs = plt.subplots(2, 2, subplot_kw=dict(projection="polar"))
axs[0, 0].plot(x, y)
axs[1, 1].scatter(x, y)
# Share a X axis with each column of subplots
plt.subplots(2, 2, sharex='col')
# Share a Y axis with each row of subplots
plt.subplots(2, 2, sharey='row')
# Share both X and Y axes with all subplots
plt.subplots(2, 2, sharex='all', sharey='all')
# Note that this is the same as
plt.subplots(2, 2, sharex=True, sharey=True)
# Create figure number 10 with a single subplot
# and clears it if it already exists.
fig, ax = plt.subplots(num=10, clear=True)
Examples using matplotlib.pyplot.subplots
Bar Label Demo
Stacked bar chart
Grouped bar chart with labels
Horizontal bar chart
Broken Barh
Plotting categorical variables
Plotting the coherence of two signals
CSD Demo
Curve with error band
Errorbar subsampling
Eventplot Demo
Filled polygon
Fill Between and Alpha
Filling the area between lines
Fill Betweenx Demo
Hatch-filled histograms
Bar chart with gradients
Hat graph
Discrete distribution as horizontal bar chart
Customizing dashed line styles
Lines with a ticked patheffect
Marker reference
Multicolored lines
Psd Demo
Scatter Custom Symbol
Scatter Demo2
Scatter plot with pie chart markers
Marker examples
Scatter plots with a legend
Simple Plot
Using span_where
Spectrum Representations
Stackplots and streamgraphs
Stairs Demo
Creating a timeline with lines, dates, and text
hlines and vlines
Cross- and Auto-Correlation Demo
Affine transform of an image
Wind Barbs
Contour Corner Mask
Contour Demo
Contour Image
Contour Label Demo
Contourf Demo
Contourf Hatching
Contourf and log color scale
Contouring the solution space of optimizations
BboxImage Demo
Creating annotated heatmaps
Image antialiasing
Clipping images with patches
Image Demo
Image Masked
Image Nonuniform
Blend transparency with color in 2D images
Modifying the coordinate formatter
Interpolations for imshow
Contour plot of irregularly spaced data
Multi Image
Pcolor Demo
pcolormesh grids and shading
pcolormesh
QuadMesh Demo
Advanced quiver and quiverkey functions
Quiver Simple Demo
Shading example
Spectrogram Demo
Spy Demos
Tricontour Demo
Tricontour Smooth Delaunay
Tricontour Smooth User
Trigradient Demo
Triinterp Demo
Tripcolor Demo
Triplot Demo
Watermark image
Axes box aspect
Axes Demo
Controlling view limits using margins and sticky_edges
Axes Props
axhspan Demo
Equal axis aspect ratio
Axis Label Position
Broken Axis
Placing Colorbars
Resizing axes with constrained layout
Resizing axes with tight layout
Different scales on the same axes
Figure size in different units
Figure labels: suptitle, supxlabel, supylabel
Creating adjacent subplots
Combining two subplots using subplots and GridSpec
Invert Axes
Secondary Axis
Figure subfigures
Multiple subplots
Creating multiple subplots using plt.subplots
Plots with different scales
Zoom region inset axes
Percentiles as horizontal bar chart
Artist customization in box plots
Box plots with custom fill colors
Boxplots
Box plot vs. violin plot comparison
Boxplot drawer function
Plot a confidence ellipse of a two-dimensional dataset
Violin plot customization
Errorbar function
Different ways of specifying error bars
Including upper and lower limits in error bars
Creating boxes from error bars using PatchCollection
Hexagonal binned plot
Histograms
Using histograms to plot a cumulative distribution
Some features of the histogram (hist) function
Demo of the histogram function's different histtype settings
The histogram (hist) function with multiple data sets
Producing multiple histograms side by side
Time Series Histogram
Violin plot basics
Basic pie chart
Pie Demo2
Bar of pie
Nested pie charts
Labeling a pie and a donut
Polar plot
Using accented text in matplotlib
Scale invariant angle label
Annotating Plots
Composing Custom Legends
Date tick labels
Custom tick formatter for time series
AnnotationBbox demo
Using a text as a Path
Labeling ticks using engineering notation
Figure legend demo
Configuring the font family
Using a ttf font file in Matplotlib
Font table
Legend using pre-defined labels
Legend Demo
Artist within an artist
Mathtext
Math fontfamily
Multiline
Placing text boxes
Rendering math equations using TeX
Precise text layout
Default text rotation demonstration
Text Rotation Relative To Line
Title positioning
Text watermark
Align y-labels
Annotate Transform
Annotating a plot
Programmatically controlling subplot adjustment
Boxplot Demo
Dollar Ticks
Color Demo
Color by y-value
Colors in the default property cycle
Colorbar
Colormap reference
Creating a colormap from a list of colors
List of named colors
Arrow guide
Reference for Matplotlib artists
Line, Poly and RegularPoly Collection with autoscaling
Compound path
Dolphins
Mmh Donuts!!!
Ellipse Collection
Ellipse Demo
Drawing fancy boxes
Hatch style reference
Line Collection
Circles, Wedges and Polygons
PathPatch object
Bezier Curve
Bayesian Methods for Hackers style sheet
Dark background style sheet
FiveThirtyEight style sheet
ggplot style sheet
Grayscale style sheet
Style sheets reference
Anchored Direction Arrow
HBoxDivider demo
Showing RGB channels using RGBAxes
Adding a colorbar to inset axes
Colorbar with AxesDivider
Controlling the position and size of colorbars with Inset Axes
Inset Locator Demo
Inset Locator Demo2
Scatter Histogram (Locatable Axes)
Simple Anchored Artists
Bachelor's degrees by gender
Integral as the area under a curve
Decay
Animated histogram
pyplot animation
The Bayes update
Animated image using a precomputed list of images
Pausing and Resuming an Animation
Animated line plot
Oscilloscope
Mouse move and click events
Data Browser
Figure/Axes enter and leave events
Image Slices Viewer
Keypress event
Legend Picking
Looking Glass
Path Editor
Pick Event Demo
Pick Event Demo2
Poly Editor
Pong
Resampling Data
Timers
Trifinder Event Demo
Viewlims
Zoom Window
Frontpage 3D example
Frontpage contour example
Frontpage histogram example
Frontpage plot example
Anchored Artists
Changing colors of lines intersecting a box
Manual Contour
Coords Report
Cross hair cursor
Custom projection
AGG filter
Ribbon Box
Findobj Demo
Building histograms using Rectangles and PolyCollections
Plotting with keywords
Multiprocess
Packed-bubble chart
Patheffect Demo
Pythonic Matplotlib
Rasterization for vector graphics
TickedStroke patheffect
Zorder Demo
Custom hillshading in a 3D surface plot
3D stem
3D surface (colormap)
3D wireframe plots in one direction
Loglog Aspect
Log Bar
Log Demo
Log Axis
Logit Demo
Exploring normalizations
Scales
Symlog Demo
Hillshading
Anscombe's quartet
Left ventricle bullseye
MRI
Radar chart (aka spider or star chart)
Topographic hillshading
Centered spines with arrows
Multiple Yaxis With Spines
Spines
Custom spine bounds
Dropped spines
Automatically setting tick positions
Centering labels between ticks
Colorbar Tick Labelling
Custom Ticker1
Formatting date ticks using ConciseDateFormatter
Date Demo Convert
Placing date ticks using recurrence rules
Date Index Formatter
Date Precision and Epochs
Major and minor ticks
The default tick formatter
Tick formatters
Tick locators
Set default y-axis tick labels on the right
Setting tick labels from a list of values
Set default x-axis tick labels on the top
Annotation with units
Artist tests
Bar demo with units
Group barchart with units
Evans test
Radian ticks
Inches and Centimeters
Unit handling
pyplot with GTK3
pyplot with GTK4
SVG Tooltip
Anchored Box04
Annotate Explain
Annotate Simple01
Annotate Simple02
Annotate Simple03
Annotate Simple04
Annotate Simple Coord01
Annotate Simple Coord02
Annotate Simple Coord03
Annotate Text Arrow
Interactive Adjustment of Colormap Range
Colormap Normalizations
Colormap Normalizations Symlognorm
Connect Simple01
Connection styles for annotations
Custom box styles
Pgf Fonts
Pgf Preamble
Pgf Texsystem
Simple Annotate01
Simple Legend02
Annotated Cursor
Buttons
Check Buttons
Cursor
Lasso Selector
Mouse Cursor
Multicursor
Polygon Selector
Radio Buttons
Thresholding an Image with RangeSlider
Slider
Snapping Sliders to Discrete Values
Span Selector
Textbox
Basic Usage
The Lifecycle of a Plot
Artist tutorial
Legend guide
Styling with cycler
Constrained Layout Guide
Tight Layout guide
Arranging multiple Axes in a Figure
Autoscaling
Faster rendering by using blitting
Path Tutorial
Transformations Tutorial
Specifying Colors
Customized Colorbars Tutorial
Creating Colormaps in Matplotlib
Colormap Normalization
Choosing Colormaps in Matplotlib
Text in Matplotlib Plots
Annotations
plot(x, y)
scatter(x, y)
bar(x, height) / barh(y, width)
stem(x, y)
step(x, y)
fill_between(x, y1, y2)
imshow(Z)
pcolormesh(X, Y, Z)
contour(X, Y, Z)
contourf(X, Y, Z)
barbs(X, Y, U, V)
quiver(X, Y, U, V)
streamplot(X, Y, U, V)
hist(x)
boxplot(X)
errorbar(x, y, yerr, xerr)
violinplot(D)
eventplot(D)
hist2d(x, y)
hexbin(x, y, C)
pie(x)
tricontour(x, y, z)
tricontourf(x, y, z)
tripcolor(x, y, z)
triplot(x, y)
|
matplotlib._as_gen.matplotlib.pyplot.subplots
|
matplotlib.pyplot.subplots_adjust matplotlib.pyplot.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)[source]
Adjust the subplot layout parameters. Unset parameters are left unmodified; initial values are given by rcParams["figure.subplot.[name]"]. Parameters
leftfloat, optional
The position of the left edge of the subplots, as a fraction of the figure width.
rightfloat, optional
The position of the right edge of the subplots, as a fraction of the figure width.
bottomfloat, optional
The position of the bottom edge of the subplots, as a fraction of the figure height.
topfloat, optional
The position of the top edge of the subplots, as a fraction of the figure height.
wspacefloat, optional
The width of the padding between subplots, as a fraction of the average Axes width.
hspacefloat, optional
The height of the padding between subplots, as a fraction of the average Axes height.
Examples using matplotlib.pyplot.subplots_adjust
Contour plot of irregularly spaced data
Subplots spacings and margins
Violin plot customization
Controlling style of text and labels using a dictionary
Parasite axis demo
Table Demo
Rotating custom tick labels
Buttons
Check Buttons
Radio Buttons
Thresholding an Image with RangeSlider
Slider
Snapping Sliders to Discrete Values
Pyplot tutorial
|
matplotlib._as_gen.matplotlib.pyplot.subplots_adjust
|
matplotlib.pyplot.summer matplotlib.pyplot.summer()[source]
Set the colormap to 'summer'. 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._as_gen.matplotlib.pyplot.summer
|
matplotlib.pyplot.suptitle matplotlib.pyplot.suptitle(t, **kwargs)[source]
Add a centered suptitle to the figure. Parameters
tstr
The suptitle text.
xfloat, default: 0.5
The x location of the text in figure coordinates.
yfloat, default: 0.98
The y location of the text in figure coordinates.
horizontalalignment, ha{'center', 'left', 'right'}, default: center
The horizontal alignment of the text relative to (x, y).
verticalalignment, va{'top', 'center', 'bottom', 'baseline'}, default: top
The vertical alignment of the text relative to (x, y).
fontsize, sizedefault: rcParams["figure.titlesize"] (default: 'large')
The font size of the text. See Text.set_size for possible values.
fontweight, weightdefault: rcParams["figure.titleweight"] (default: 'normal')
The font weight of the text. See Text.set_weight for possible values. Returns
text
The Text instance of the suptitle. Other Parameters
fontpropertiesNone or dict, optional
A dict of font properties. If fontproperties is given the default values for font size and weight are taken from the FontProperties defaults. rcParams["figure.titlesize"] (default: 'large') and rcParams["figure.titleweight"] (default: 'normal') are ignored in this case. **kwargs
Additional kwargs are matplotlib.text.Text properties.
Examples using matplotlib.pyplot.suptitle
Nested Gridspecs
Pyplot tutorial
Constrained Layout Guide
|
matplotlib._as_gen.matplotlib.pyplot.suptitle
|
matplotlib.pyplot.switch_backend matplotlib.pyplot.switch_backend(newbackend)[source]
Close all open figures and set the Matplotlib backend. The argument is case-insensitive. Switching to an interactive backend is possible only if no event loop for another interactive backend has started. Switching to and from non-interactive backends is always possible. Parameters
newbackendstr
The name of the backend to use.
|
matplotlib._as_gen.matplotlib.pyplot.switch_backend
|
matplotlib.pyplot.table matplotlib.pyplot.table(cellText=None, cellColours=None, cellLoc='right', colWidths=None, rowLabels=None, rowColours=None, rowLoc='left', colLabels=None, colColours=None, colLoc='center', loc='bottom', bbox=None, edges='closed', **kwargs)[source]
Add a table to an Axes. At least one of cellText or cellColours must be specified. These parameters must be 2D lists, in which the outer lists define the rows and the inner list define the column values per row. Each row must have the same number of elements. The table can optionally have row and column headers, which are configured using rowLabels, rowColours, rowLoc and colLabels, colColours, colLoc respectively. For finer grained control over tables, use the Table class and add it to the axes with Axes.add_table. Parameters
cellText2D list of str, optional
The texts to place into the table cells. Note: Line breaks in the strings are currently not accounted for and will result in the text exceeding the cell boundaries.
cellColours2D list of colors, optional
The background colors of the cells.
cellLoc{'left', 'center', 'right'}, default: 'right'
The alignment of the text within the cells.
colWidthslist of float, optional
The column widths in units of the axes. If not given, all columns will have a width of 1 / ncols.
rowLabelslist of str, optional
The text of the row header cells.
rowColourslist of colors, optional
The colors of the row header cells.
rowLoc{'left', 'center', 'right'}, default: 'left'
The text alignment of the row header cells.
colLabelslist of str, optional
The text of the column header cells.
colColourslist of colors, optional
The colors of the column header cells.
colLoc{'left', 'center', 'right'}, default: 'left'
The text alignment of the column header cells.
locstr, optional
The position of the cell with respect to ax. This must be one of the codes.
bboxBbox, optional
A bounding box to draw the table into. If this is not None, this overrides loc.
edgessubstring of 'BRTL' or {'open', 'closed', 'horizontal', 'vertical'}
The cell edges to be drawn with a line. See also visible_edges. Returns
Table
The created table. Other Parameters
**kwargs
Table 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
clip_box Bbox
clip_on bool
clip_path Patch or (Path, Transform) or None
figure Figure
fontsize float
gid str
in_layout bool
label object
path_effects AbstractPathEffect
picker None or bool or float or callable
rasterized bool
sketch_params (scale: float, length: float, randomness: float)
snap bool or None
transform Transform
url str
visible bool
zorder float
Examples using matplotlib.pyplot.table
Table Demo
|
matplotlib._as_gen.matplotlib.pyplot.table
|
matplotlib.pyplot.text matplotlib.pyplot.text(x, y, s, fontdict=None, **kwargs)[source]
Add text to the Axes. Add the text s to the Axes at location x, y in data coordinates. Parameters
x, yfloat
The position to place the text. By default, this is in data coordinates. The coordinate system can be changed using the transform parameter.
sstr
The text.
fontdictdict, default: None
A dictionary to override the default text properties. If fontdict is None, the defaults are determined by rcParams. Returns
Text
The created Text instance. 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 Examples Individual keyword arguments can be used to override any given parameter: >>> text(x, y, s, fontsize=12)
The default transform specifies that text is in data coords, alternatively, you can specify text in axis coords ((0, 0) is lower-left and (1, 1) is upper-right). The example below places text in the center of the Axes: >>> text(0.5, 0.5, 'matplotlib', horizontalalignment='center',
... verticalalignment='center', transform=ax.transAxes)
You can put a rectangular box around the text instance (e.g., to set a background color) by using the keyword bbox. bbox is a dictionary of Rectangle properties. For example: >>> text(x, y, s, bbox=dict(facecolor='red', alpha=0.5))
Examples using matplotlib.pyplot.text
Figure size in different units
Auto-wrapping text
Styling text boxes
Controlling style of text and labels using a dictionary
Pyplot Mathtext
Pyplot Text
Reference for Matplotlib artists
Close Event
transforms.offset_copy
Pyplot tutorial
Path effects guide
Text properties and layout
Annotations
|
matplotlib._as_gen.matplotlib.pyplot.text
|
matplotlib.pyplot.thetagrids matplotlib.pyplot.thetagrids(angles=None, labels=None, fmt=None, **kwargs)[source]
Get or set the theta gridlines on the current polar plot. Call signatures: lines, labels = thetagrids()
lines, labels = thetagrids(angles, labels=None, fmt=None, **kwargs)
When called with no arguments, thetagrids simply returns the tuple (lines, labels). When called with arguments, the labels will appear at the specified angles. Parameters
anglestuple with floats, degrees
The angles of the theta gridlines.
labelstuple with strings or None
The labels to use at each radial gridline. The projections.polar.ThetaFormatter will be used if None.
fmtstr or None
Format string used in matplotlib.ticker.FormatStrFormatter. For example '%f'. Note that the angle in radians will be used. Returns
lineslist of lines.Line2D
The theta gridlines.
labelslist of text.Text
The tick labels. Other Parameters
**kwargs
kwargs are optional Text properties for the labels. See also pyplot.rgrids
projections.polar.PolarAxes.set_thetagrids
Axis.get_gridlines
Axis.get_ticklabels
Examples # set the locations of the angular gridlines
lines, labels = thetagrids(range(45, 360, 90))
# set the locations and labels of the angular gridlines
lines, labels = thetagrids(range(45, 360, 90), ('NE', 'NW', 'SW', 'SE'))
|
matplotlib._as_gen.matplotlib.pyplot.thetagrids
|
matplotlib.pyplot.tick_params matplotlib.pyplot.tick_params(axis='both', **kwargs)[source]
Change the appearance of ticks, tick labels, and gridlines. Tick properties that are not explicitly set using the keyword arguments remain unchanged unless reset is True. Parameters
axis{'x', 'y', 'both'}, default: 'both'
The axis to which the parameters are applied.
which{'major', 'minor', 'both'}, default: 'major'
The group of ticks to which the parameters are applied.
resetbool, default: False
Whether to reset the ticks to defaults before updating them. Other Parameters
direction{'in', 'out', 'inout'}
Puts ticks inside the axes, outside the axes, or both.
lengthfloat
Tick length in points.
widthfloat
Tick width in points.
colorcolor
Tick color.
padfloat
Distance in points between tick and label.
labelsizefloat or str
Tick label font size in points or as a string (e.g., 'large').
labelcolorcolor
Tick label color.
colorscolor
Tick color and label color.
zorderfloat
Tick and label zorder.
bottom, top, left, rightbool
Whether to draw the respective ticks.
labelbottom, labeltop, labelleft, labelrightbool
Whether to draw the respective tick labels.
labelrotationfloat
Tick label rotation
grid_colorcolor
Gridline color.
grid_alphafloat
Transparency of gridlines: 0 (transparent) to 1 (opaque).
grid_linewidthfloat
Width of gridlines in points.
grid_linestylestr
Any valid Line2D line style spec. Examples ax.tick_params(direction='out', length=6, width=2, colors='r',
grid_color='r', grid_alpha=0.5)
This will make all major ticks be red, pointing out of the box, and with dimensions 6 points by 2 points. Tick labels will also be red. Gridlines will be red and translucent.
Examples using matplotlib.pyplot.tick_params
Shared Axis
|
matplotlib._as_gen.matplotlib.pyplot.tick_params
|
matplotlib.pyplot.ticklabel_format matplotlib.pyplot.ticklabel_format(*, axis='both', style='', scilimits=None, useOffset=None, useLocale=None, useMathText=None)[source]
Configure the ScalarFormatter used by default for linear axes. If a parameter is not set, the corresponding property of the formatter is left unchanged. Parameters
axis{'x', 'y', 'both'}, default: 'both'
The axis to configure. Only major ticks are affected.
style{'sci', 'scientific', 'plain'}
Whether to use scientific notation. The formatter default is to use scientific notation.
scilimitspair of ints (m, n)
Scientific notation is used only for numbers outside the range 10m to 10n (and only if the formatter is configured to use scientific notation at all). Use (0, 0) to include all numbers. Use (m, m) where m != 0 to fix the order of magnitude to 10m. The formatter default is rcParams["axes.formatter.limits"] (default: [-5, 6]).
useOffsetbool or float
If True, the offset is calculated as needed. If False, no offset is used. If a numeric value, it sets the offset. The formatter default is rcParams["axes.formatter.useoffset"] (default: True).
useLocalebool
Whether to format the number using the current locale or using the C (English) locale. This affects e.g. the decimal separator. The formatter default is rcParams["axes.formatter.use_locale"] (default: False).
useMathTextbool
Render the offset and scientific notation in mathtext. The formatter default is rcParams["axes.formatter.use_mathtext"] (default: False). Raises
AttributeError
If the current formatter is not a ScalarFormatter.
|
matplotlib._as_gen.matplotlib.pyplot.ticklabel_format
|
matplotlib.pyplot.tight_layout matplotlib.pyplot.tight_layout(*, pad=1.08, h_pad=None, w_pad=None, rect=None)[source]
Adjust the padding between and around subplots. To exclude an artist on the Axes from the bounding box calculation that determines the subplot parameters (i.e. legend, or annotation), set a.set_in_layout(False) for that artist. Parameters
padfloat, default: 1.08
Padding between the figure edge and the edges of subplots, as a fraction of the font size.
h_pad, w_padfloat, default: pad
Padding (height/width) between edges of adjacent subplots, as a fraction of the font size.
recttuple (left, bottom, right, top), default: (0, 0, 1, 1)
A rectangle in normalized figure coordinates into which the whole subplots area (including labels) will fit. See also Figure.set_tight_layout
pyplot.tight_layout
Examples using matplotlib.pyplot.tight_layout
Linestyles
Marker examples
Creating annotated heatmaps
Interpolations for imshow
Streamplot
Resizing axes with tight layout
Labeling ticks using engineering notation
Figure legend demo
Reference for Matplotlib artists
Zorder Demo
3D wireframe plots in one direction
MRI With EEG
Tick locators
Tight Layout guide
|
matplotlib._as_gen.matplotlib.pyplot.tight_layout
|
matplotlib.pyplot.title matplotlib.pyplot.title(label, fontdict=None, loc=None, pad=None, *, y=None, **kwargs)[source]
Set a title for the Axes. Set one of the three available Axes titles. The available titles are positioned above the Axes in the center, flush with the left edge, and flush with the right edge. Parameters
labelstr
Text to use for the title
fontdictdict
A dictionary controlling the appearance of the title text, the default fontdict is: {'fontsize': rcParams['axes.titlesize'],
'fontweight': rcParams['axes.titleweight'],
'color': rcParams['axes.titlecolor'],
'verticalalignment': 'baseline',
'horizontalalignment': loc}
loc{'center', 'left', 'right'}, default: rcParams["axes.titlelocation"] (default: 'center')
Which title to set.
yfloat, default: rcParams["axes.titley"] (default: None)
Vertical Axes loation for the title (1.0 is the top). If None (the default), y is determined automatically to avoid decorators on the Axes.
padfloat, default: rcParams["axes.titlepad"] (default: 6.0)
The offset of the title from the top of the Axes, in points. Returns
Text
The matplotlib text instance representing the title Other Parameters
**kwargsText properties
Other keyword arguments are text properties, see Text for a list of valid text properties.
Examples using matplotlib.pyplot.title
prop_cycle property markevery in rcParams
Plotting masked and NaN values
Stairs Demo
Step Demo
Geographic Projections
Multiple subplots
Controlling style of text and labels using a dictionary
Title positioning
Pyplot Mathtext
Pyplot Text
Solarized Light stylesheet
Interactive functions
Findobj Demo
Multipage PDF
Set and get properties
Table Demo
Zorder Demo
Custom scale
The Sankey class
SVG Histogram
Basic Usage
Pyplot tutorial
|
matplotlib._as_gen.matplotlib.pyplot.title
|
matplotlib.pyplot.tricontour matplotlib.pyplot.tricontour(*args, **kwargs)[source]
Draw contour lines on an unstructured triangular grid. The triangulation can be specified in one of two ways; either tricontour(triangulation, ...)
where triangulation is a Triangulation object, or tricontour(x, y, ...)
tricontour(x, y, triangles, ...)
tricontour(x, y, triangles=triangles, ...)
tricontour(x, y, mask=mask, ...)
tricontour(x, y, triangles, mask=mask, ...)
in which case a Triangulation object will be created. See that class' docstring for an explanation of these cases. The remaining arguments may be: tricontour(..., Z)
where Z is the array of values to contour, one per point in the triangulation. The level values are chosen automatically. tricontour(..., Z, levels)
contour up to levels+1 automatically chosen contour levels (levels intervals). tricontour(..., Z, levels)
draw contour lines at the values specified in sequence levels, which must be in increasing order. tricontour(Z, **kwargs)
Use keyword arguments to control colors, linewidth, origin, cmap ... see below for more details. Parameters
triangulationTriangulation, optional
The unstructured triangular grid. If specified, then x, y, triangles, and mask are not accepted.
x, yarray-like, optional
The coordinates of the values in Z.
triangles(ntri, 3) array-like of int, optional
For each triangle, the indices of the three points that make up the triangle, ordered in an anticlockwise manner. If not specified, the Delaunay triangulation is calculated.
mask(ntri,) array-like of bool, optional
Which triangles are masked out.
Z2D 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
TriContourSet
Other Parameters
colorscolor string or sequence of colors, optional
The colors of the levels, i.e., the contour lines. 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 tricontour-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 TriContourSet does not get notified if properties of its colormap are changed. Therefore, an explicit call to ContourSet.changed() is needed after modifying the colormap. The explicit call can be left out, if a colorbar is assigned to the TriContourSet because it internally calls ContourSet.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).
linewidthsfloat or array-like, default: rcParams["contour.linewidth"] (default: None)
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
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.
|
matplotlib._as_gen.matplotlib.pyplot.tricontour
|
matplotlib.pyplot.tricontourf matplotlib.pyplot.tricontourf(*args, **kwargs)[source]
Draw contour regions on an unstructured triangular grid. The triangulation can be specified in one of two ways; either tricontourf(triangulation, ...)
where triangulation is a Triangulation object, or tricontourf(x, y, ...)
tricontourf(x, y, triangles, ...)
tricontourf(x, y, triangles=triangles, ...)
tricontourf(x, y, mask=mask, ...)
tricontourf(x, y, triangles, mask=mask, ...)
in which case a Triangulation object will be created. See that class' docstring for an explanation of these cases. The remaining arguments may be: tricontourf(..., Z)
where Z is the array of values to contour, one per point in the triangulation. The level values are chosen automatically. tricontourf(..., Z, levels)
contour up to levels+1 automatically chosen contour levels (levels intervals). tricontourf(..., Z, levels)
draw contour regions at the values specified in sequence levels, which must be in increasing order. tricontourf(Z, **kwargs)
Use keyword arguments to control colors, linewidth, origin, cmap ... see below for more details. Parameters
triangulationTriangulation, optional
The unstructured triangular grid. If specified, then x, y, triangles, and mask are not accepted.
x, yarray-like, optional
The coordinates of the values in Z.
triangles(ntri, 3) array-like of int, optional
For each triangle, the indices of the three points that make up the triangle, ordered in an anticlockwise manner. If not specified, the Delaunay triangulation is calculated.
mask(ntri,) array-like of bool, optional
Which triangles are masked out.
Z2D 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
TriContourSet
Other Parameters
colorscolor string or sequence of colors, optional
The colors of the levels, i.e., the contour regions. 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 tricontourf-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 TriContourSet does not get notified if properties of its colormap are changed. Therefore, an explicit call to ContourSet.changed() is needed after modifying the colormap. The explicit call can be left out, if a colorbar is assigned to the TriContourSet because it internally calls ContourSet.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).
hatcheslist[str], optional
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. Notes tricontourf 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).
|
matplotlib._as_gen.matplotlib.pyplot.tricontourf
|
matplotlib.pyplot.tripcolor matplotlib.pyplot.tripcolor(*args, alpha=1.0, norm=None, cmap=None, vmin=None, vmax=None, shading='flat', facecolors=None, **kwargs)[source]
Create a pseudocolor plot of an unstructured triangular grid. The triangulation can be specified in one of two ways; either: tripcolor(triangulation, ...)
where triangulation is a Triangulation object, or tripcolor(x, y, ...)
tripcolor(x, y, triangles, ...)
tripcolor(x, y, triangles=triangles, ...)
tripcolor(x, y, mask=mask, ...)
tripcolor(x, y, triangles, mask=mask, ...)
in which case a Triangulation object will be created. See Triangulation for a explanation of these possibilities. The next argument must be C, the array of color values, either one per point in the triangulation if color values are defined at points, or one per triangle in the triangulation if color values are defined at triangles. If there are the same number of points and triangles in the triangulation it is assumed that color values are defined at points; to force the use of color values at triangles use the kwarg facecolors=C instead of just C. shading may be 'flat' (the default) or 'gouraud'. If shading is 'flat' and C values are defined at points, the color values used for each triangle are from the mean C of the triangle's three points. If shading is 'gouraud' then color values must be defined at points. The remaining kwargs are the same as for pcolor.
|
matplotlib._as_gen.matplotlib.pyplot.tripcolor
|
matplotlib.pyplot.triplot matplotlib.pyplot.triplot(*args, **kwargs)[source]
Draw a unstructured triangular grid as lines and/or markers. The triangulation to plot can be specified in one of two ways; either: triplot(triangulation, ...)
where triangulation is a Triangulation object, or triplot(x, y, ...)
triplot(x, y, triangles, ...)
triplot(x, y, triangles=triangles, ...)
triplot(x, y, mask=mask, ...)
triplot(x, y, triangles, mask=mask, ...)
in which case a Triangulation object will be created. See Triangulation for a explanation of these possibilities. The remaining args and kwargs are the same as for plot. Returns
linesLine2D
The drawn triangles edges.
markersLine2D
The drawn marker nodes.
|
matplotlib._as_gen.matplotlib.pyplot.triplot
|
matplotlib.pyplot.twinx matplotlib.pyplot.twinx(ax=None)[source]
Make and return a second axes that shares the x-axis. The new axes will overlay ax (or the current axes if ax is None), and its ticks will be on the right. Examples Plots with different scales
|
matplotlib._as_gen.matplotlib.pyplot.twinx
|
matplotlib.pyplot.twiny matplotlib.pyplot.twiny(ax=None)[source]
Make and return a second axes that shares the y-axis. The new axes will overlay ax (or the current axes if ax is None), and its ticks will be on the top. Examples Plots with different scales
|
matplotlib._as_gen.matplotlib.pyplot.twiny
|
matplotlib.pyplot.uninstall_repl_displayhook matplotlib.pyplot.uninstall_repl_displayhook()[source]
Uninstall the Matplotlib display hook. Warning Need IPython >= 2 for this to work. For IPython < 2 will raise a NotImplementedError Warning If you are using vanilla python and have installed another display hook, this will reset sys.displayhook to what ever function was there when Matplotlib installed its displayhook, possibly discarding your changes.
|
matplotlib._as_gen.matplotlib.pyplot.uninstall_repl_displayhook
|
matplotlib.pyplot.violinplot matplotlib.pyplot.violinplot(dataset, positions=None, vert=True, widths=0.5, showmeans=False, showextrema=True, showmedians=False, quantiles=None, points=100, bw_method=None, *, data=None)[source]
Make a violin plot. Make a violin plot for each column of dataset or each vector in sequence dataset. Each filled area extends to represent the entire data range, with optional lines at the mean, the median, the minimum, the maximum, and user-specified quantiles. Parameters
datasetArray or a sequence of vectors.
The input data.
positionsarray-like, default: [1, 2, ..., n]
The positions of the violins. The ticks and limits are automatically set to match the positions.
vertbool, default: True.
If true, creates a vertical violin plot. Otherwise, creates a horizontal violin plot.
widthsarray-like, default: 0.5
Either a scalar or a vector that sets the maximal width of each violin. The default is 0.5, which uses about half of the available horizontal space.
showmeansbool, default: False
If True, will toggle rendering of the means.
showextremabool, default: True
If True, will toggle rendering of the extrema.
showmediansbool, default: False
If True, will toggle rendering of the medians.
quantilesarray-like, default: None
If not None, set a list of floats in interval [0, 1] for each violin, which stands for the quantiles that will be rendered for that violin.
pointsint, default: 100
Defines the number of points to evaluate each of the gaussian kernel density estimations at.
bw_methodstr, scalar or callable, optional
The method used to calculate the estimator bandwidth. This can be 'scott', 'silverman', a scalar constant or a callable. If a scalar, this will be used directly as kde.factor. If a callable, it should take a GaussianKDE instance as its only parameter and return a scalar. If None (default), 'scott' is used.
dataindexable object, optional
If given, the following parameters also accept a string s, which is interpreted as data[s] (unless this raises an exception): dataset Returns
dict
A dictionary mapping each component of the violinplot to a list of the corresponding collection instances created. The dictionary has the following keys:
bodies: A list of the PolyCollection instances containing the filled area of each violin.
cmeans: A LineCollection instance that marks the mean values of each of the violin's distribution.
cmins: A LineCollection instance that marks the bottom of each violin's distribution.
cmaxes: A LineCollection instance that marks the top of each violin's distribution.
cbars: A LineCollection instance that marks the centers of each violin's distribution.
cmedians: A LineCollection instance that marks the median values of each of the violin's distribution.
cquantiles: A LineCollection instance created to identify the quantile values of each of the violin's distribution.
|
matplotlib._as_gen.matplotlib.pyplot.violinplot
|
matplotlib.pyplot.viridis matplotlib.pyplot.viridis()[source]
Set the colormap to 'viridis'. 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._as_gen.matplotlib.pyplot.viridis
|
matplotlib.pyplot.vlines matplotlib.pyplot.vlines(x, ymin, ymax, colors=None, linestyles='solid', label='', *, data=None, **kwargs)[source]
Plot vertical lines at each x from ymin to ymax. Parameters
xfloat or array-like
x-indexes where to plot the lines.
ymin, ymaxfloat 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): x, ymin, ymax, colors
**kwargsLineCollection properties.
See also hlines
horizontal lines axvline
vertical line across the Axes
|
matplotlib._as_gen.matplotlib.pyplot.vlines
|
matplotlib.pyplot.waitforbuttonpress matplotlib.pyplot.waitforbuttonpress(timeout=- 1)[source]
Blocking call to interact with the figure. Wait for user input and return True if a key was pressed, False if a mouse button was pressed and None if no input was given within timeout seconds. Negative values deactivate timeout.
Examples using matplotlib.pyplot.waitforbuttonpress
Interactive functions
|
matplotlib._as_gen.matplotlib.pyplot.waitforbuttonpress
|
matplotlib.pyplot.winter matplotlib.pyplot.winter()[source]
Set the colormap to 'winter'. 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._as_gen.matplotlib.pyplot.winter
|
matplotlib.pyplot.xcorr matplotlib.pyplot.xcorr(x, y, normed=True, detrend=<function detrend_none>, usevlines=True, maxlags=10, *, data=None, **kwargs)[source]
Plot the cross correlation between x and y. The correlation with lag k is defined as \(\sum_n x[n+k] \cdot y^*[n]\), where \(y^*\) is the complex conjugate of \(y\). Parameters
x, yarray-like of length n
detrendcallable, default: mlab.detrend_none (no detrending)
A detrending function applied to x and y. It must have the signature detrend(x: np.ndarray) -> np.ndarray
normedbool, default: True
If True, input vectors are normalised to unit length.
usevlinesbool, default: True
Determines the plot style. If True, vertical lines are plotted from 0 to the xcorr value using Axes.vlines. Additionally, a horizontal line is plotted at y=0 using Axes.axhline. If False, markers are plotted at the xcorr values using Axes.plot.
maxlagsint, default: 10
Number of lags to show. If None, will return all 2 * len(x) - 1 lags. Returns
lagsarray (length 2*maxlags+1)
The lag vector.
carray (length 2*maxlags+1)
The auto correlation vector.
lineLineCollection or Line2D
Artist added to the Axes of the correlation:
LineCollection if usevlines is True.
Line2D if usevlines is False.
bLine2D or None
Horizontal line at 0 if usevlines is True None usevlines is False. Other Parameters
linestyleLine2D property, optional
The linestyle for plotting the data points. Only used if usevlines is False.
markerstr, default: 'o'
The marker for plotting the data points. Only used if usevlines is False.
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
Additional parameters are passed to Axes.vlines and Axes.axhline if usevlines is True; otherwise they are passed to Axes.plot. Notes The cross correlation is performed with numpy.correlate with mode = "full".
|
matplotlib._as_gen.matplotlib.pyplot.xcorr
|
matplotlib.pyplot.xkcd matplotlib.pyplot.xkcd(scale=1, length=100, randomness=2)[source]
Turn on xkcd sketch-style drawing mode. This will only have effect on things drawn after this function is called. For best results, the "Humor Sans" font should be installed: it is not included with Matplotlib. Parameters
scalefloat, optional
The amplitude of the wiggle perpendicular to the source line.
lengthfloat, optional
The length of the wiggle along the line.
randomnessfloat, optional
The scale factor by which the length is shrunken or expanded. Notes This function works by a number of rcParams, so it will probably override others you have set before. If you want the effects of this function to be temporary, it can be used as a context manager, for example: with plt.xkcd():
# This figure will be in XKCD-style
fig1 = plt.figure()
# ...
# This figure will be in regular style
fig2 = plt.figure()
Examples using matplotlib.pyplot.xkcd
XKCD
|
matplotlib._as_gen.matplotlib.pyplot.xkcd
|
matplotlib.pyplot.xlabel matplotlib.pyplot.xlabel(xlabel, fontdict=None, labelpad=None, *, loc=None, **kwargs)[source]
Set the label for the x-axis. Parameters
xlabelstr
The label text.
labelpadfloat, default: rcParams["axes.labelpad"] (default: 4.0)
Spacing in points from the Axes bounding box including ticks and tick labels. If None, the previous value is left as is.
loc{'left', 'center', 'right'}, default: rcParams["xaxis.labellocation"] (default: 'center')
The label position. This is a high-level alternative for passing parameters x and horizontalalignment. Other Parameters
**kwargsText properties
Text properties control the appearance of the label. See also text
Documents the properties supported by Text.
Examples using matplotlib.pyplot.xlabel
Scatter Symbol
Multiple subplots
Controlling style of text and labels using a dictionary
Infinite lines
Pyplot Mathtext
Pyplot Text
Solarized Light stylesheet
Findobj Demo
Custom scale
Basic Usage
Pyplot tutorial
|
matplotlib._as_gen.matplotlib.pyplot.xlabel
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.