Plot y versus x as lines and/or markers.
Call signatures:
The coordinates of the points or line nodes are given by x, y.
The optional parameter fmt is a convenient way for defining basic formatting like color, marker and linestyle. It's a shortcut string notation described in the Notes section below.
You can use Line2D properties as keyword arguments for more control on the appearance. Line properties and fmt can be mixed. The following two calls yield identical results:
When conflicting with fmt, keyword arguments take precedence.
Plotting labelled data
There's a convenient way for plotting objects with labelled data (i.e. data that can be accessed by index obj['y']). Instead of giving the data in x and y, you can provide the object in the data parameter and just give the labels for x and y:
All indexable objects are supported. This could e.g. be a dict, a pandas.DataFrame or a structured numpy array.
Plotting multiple sets of data
There are various ways to plot multiple sets of data.
The most straight forward way is just to call plot multiple times. Example:
If x and/or y are 2D arrays a separate data set will be drawn for every column. If both x and y are 2D, they must have the same shape. If only one of them is 2D with shape (N, m) the other must have length N and will be used for every data set m.
Example:
is equivalent to:
The third way is to specify multiple sets of [x], y, [fmt] groups:
In this case, any additional keyword argument applies to all datasets. Also this syntax cannot be combined with the data parameter.
By default, each line is assigned a different style specified by a 'style cycle'. The fmt and line property parameters are only necessary if you want explicit deviations from these defaults. Alternatively, you can also change the style cycle using rcParams["axes.prop_cycle"] (default: cycler('color', ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf'])).
The horizontal / vertical coordinates of the data points. x values are optional and default to range(len(y)).
Commonly, these parameters are 1D arrays.
They can also be scalars, or two-dimensional (in that case, the columns represent separate data sets).
These arguments cannot be passed as keywords.
A format string, e.g. 'ro' for red circles. See the Notes section for a full description of the format strings.
Format strings are just an abbreviation for quickly setting basic line properties. All of these and more can also be controlled by keyword arguments.
This argument cannot be passed as keyword.
An object with labelled data. If given, provide the label names to plot in x and y.
Note
Technically there's a slight ambiguity in calls where the second label is a valid fmt. plot('n', 'o', data=obj) could be plt(x, y) or plt(y, fmt). In such cases, the former interpretation is chosen, but a warning is issued. You may suppress the warning by adding an empty format string plot('n', 'o', '', data=obj).
A list of lines representing the plotted data.
These parameters determine if the view limits are adapted to the data limits. The values are passed on to autoscale_view.
kwargs are used to specify properties like a line label (for auto legends), linewidth, antialiasing, marker face color. Example:
If you specify multiple lines with one plot call, the kwargs apply to all those lines. In case the label object is iterable, each element is used as labels for each set of data.
Here is a list of available Line2D properties:
Property
Description
agg_filter
a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha
scalar or None
animated
bool
antialiased or aa
bool
clip_box
Bbox
clip_on
bool
clip_path
Patch or (Path, Transform) or None
color or c
color
dash_capstyle
CapStyle or {'butt', 'projecting', 'round'}
dash_joinstyle
JoinStyle or {'miter', 'round', 'bevel'}
dashes
sequence of floats (on/off ink in points) or (None, None)
data
(2, N) array or two 1D arrays
drawstyle or ds
{'default', 'steps', 'steps-pre', 'steps-mid', 'steps-post'}, default: 'default'
figure
Figure
fillstyle
{'full', 'left', 'right', 'bottom', 'top', 'none'}
gid
str
in_layout
bool
label
object
linestyle or ls
{'-', '--', '-.', ':', '', (offset, on-off-seq), ...}
linewidth or lw
float
marker
marker style string, Path or MarkerStyle
markeredgecolor or mec
color
markeredgewidth or mew
float
markerfacecolor or mfc
color
markerfacecoloralt or mfcalt
color
markersize or ms
float
markevery
None or int or (int, int) or slice or list[int] or float or (float, float) or list[bool]
path_effects
AbstractPathEffect
picker
float or callable[[Artist, Event], tuple[bool, dict]]
pickradius
float
rasterized
bool
sketch_params
(scale: float, length: float, randomness: float)
snap
bool or None
solid_capstyle
CapStyle or {'butt', 'projecting', 'round'}
solid_joinstyle
JoinStyle or {'miter', 'round', 'bevel'}
transform
unknown
url
str
visible
bool
xdata
1D array
ydata
1D array
zorder
float
See also
XY scatter plot with markers of varying size and/or color ( sometimes also called bubble chart).
Format Strings
A format string consists of a part for color, marker and line:
Each of them is optional. If not provided, the value from the style cycle is used. Exception: If line is given, but no marker, the data will be a line without markers.
Other combinations such as [color][marker][line] are also supported, but note that their parsing may be ambiguous.
Markers
character
description
'.'
point marker
','
pixel marker
'o'
circle marker
'v'
triangle_down marker
'^'
triangle_up marker
'<'
triangle_left marker
'>'
triangle_right marker
'1'
tri_down marker
'2'
tri_up marker
'3'
tri_left marker
'4'
tri_right marker
'8'
octagon marker
's'
square marker
'p'
pentagon marker
'P'
plus (filled) marker
'*'
star marker
'h'
hexagon1 marker
'H'
hexagon2 marker
'+'
plus marker
'x'
x marker
'X'
x (filled) marker
'D'
diamond marker
'd'
thin_diamond marker
'|'
vline marker
'_'
hline marker
Line Styles
character
description
'-'
solid line style
'--'
dashed line style
'-.'
dash-dot line style
':'
dotted line style
Example format strings:
Colors
The supported color abbreviations are the single letter codes
character
color
'b'
blue
'g'
green
'r'
red
'c'
cyan
'm'
magenta
'y'
yellow
'k'
black
'w'
white
and the 'CN' colors that index into the default property cycle.
If the color is the only part of the format string, you can additionally use any matplotlib.colors spec, e.g. full names ('green') or hex strings ('#008000').
Plotting categorical variables
CSD Demo
Curve with error band
EventCollection Demo
Fill Between and Alpha
Filling the area between lines
Fill Betweenx Demo
Customizing dashed line styles
Lines with a ticked patheffect
Marker reference
Markevery Demo
prop_cycle property markevery in rcParams
Psd Demo
Simple Plot
Using span_where
Creating a timeline with lines, dates, and text
hlines and vlines
Contour Corner Mask
Contour plot of irregularly spaced data
pcolormesh grids and shading
Streamplot
Spectrogram Demo
Watermark image
Aligning Labels
Axes box aspect
Axes Demo
Controlling view limits using margins and sticky_edges
Axes Props
axhspan Demo
Broken Axis
Resizing axes with constrained layout
Resizing axes with tight layout
Figure labels: suptitle, supxlabel, supylabel
Invert Axes
Secondary Axis
Sharing axis limits and views
Figure subfigures
Multiple subplots
Creating multiple subplots using plt.subplots
Plots with different scales
Boxplots
Using histograms to plot a cumulative distribution
Some features of the histogram (hist) function
Polar plot
Polar Legend
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
Labeling ticks using engineering notation
Annotation arrow style reference
Legend using pre-defined labels
Legend Demo
Mathtext
Math fontfamily
Multiline
Rendering math equations using TeX
Text Rotation Relative To Line
Title positioning
Text watermark
Annotate Transform
Annotating a plot
Annotation Polar
Programmatically controlling subplot adjustment
Dollar Ticks
Simple axes labels
Text Commands
Color Demo
Color by y-value
PathPatch object
Bezier Curve
Dark background style sheet
FiveThirtyEight style sheet
ggplot style sheet
Axes with a fixed physical size
Parasite Simple
Simple Axisline4
Axis line styles
Parasite Axes demo
Parasite axis demo
Custom spines with axisartist
Simple Axisline
Anatomy of a figure
Bachelor's degrees by gender
Integral as the area under a curve
XKCD
Decay
The Bayes update
The double pendulum problem
Animated 3D random walk
Animated line plot
MATPLOTLIB UNCHAINED
Mouse move and click events
Data Browser
Keypress event
Legend Picking
Looking Glass
Path Editor
Pick Event Demo2
Resampling Data
Timers
Frontpage histogram example
Frontpage plot example
Changing colors of lines intersecting a box
Cross hair cursor
Custom projection
Patheffect Demo
Pythonic Matplotlib
SVG Filter Line
TickedStroke patheffect
Zorder Demo
Plot 2D data on 3D plot
3D box surface plot
Parametric Curve
Lorenz Attractor
2D and 3D Axes in same Figure
Loglog Aspect
Scales
Symlog Demo
Anscombe's quartet
Radar chart (aka spider or star chart)
Centered spines with arrows
Multiple Yaxis With Spines
Spine Placement
Spines
Custom spine bounds
Centering labels between ticks
Formatting date ticks using ConciseDateFormatter
Date Demo Convert
Date Index Formatter
Date Precision and Epochs
Major and minor ticks
The default tick formatter
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
Evans test
CanvasAgg demo
Annotate Explain
Connect Simple01
Connection styles for annotations
Nested GridSpecs
Pgf Fonts
Pgf Texsystem
Simple Annotate01
Simple Legend01
Simple Legend02
Annotated Cursor
Check Buttons
Cursor
Multicursor
Radio Buttons
Rectangle and ellipse selectors
Span Selector
Textbox
Basic Usage
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
Text in Matplotlib Plots
plot(x, y)
fill_between(x, y1, y2)
tricontour(x, y, z)
tricontourf(x, y, z)
tripcolor(x, y, z)


Plot coercing the axis to treat floats as dates.
Discouraged
This method exists for historic reasons and will be deprecated in the future.
Similar to plot, this plots y vs. x as lines or markers. However, the axis labels are formatted as dates depending on xdate and ydate. Note that plot will work with datetime and numpy.datetime64 objects without resorting to this method.
The coordinates of the data points. If xdate or ydate is True, the respective values x or y are interpreted as Matplotlib dates.
The plot format string. For details, see the corresponding parameter in plot.
The time zone to use in labeling dates.
If True, the x-axis will be interpreted as Matplotlib dates.
If True, the y-axis will be interpreted as Matplotlib dates.
Objects representing the plotted data.
If given, the following parameters also accept a string s, which is interpreted as data[s] (unless this raises an exception):
x, y
Keyword arguments control the Line2D properties:
Property
Description
agg_filter
a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha
scalar or None
animated
bool
antialiased or aa
bool
clip_box
Bbox
clip_on
bool
clip_path
Patch or (Path, Transform) or None
color or c
color
dash_capstyle
CapStyle or {'butt', 'projecting', 'round'}
dash_joinstyle
JoinStyle or {'miter', 'round', 'bevel'}
dashes
sequence of floats (on/off ink in points) or (None, None)
data
(2, N) array or two 1D arrays
drawstyle or ds
{'default', 'steps', 'steps-pre', 'steps-mid', 'steps-post'}, default: 'default'
figure
Figure
fillstyle
{'full', 'left', 'right', 'bottom', 'top', 'none'}
gid
str
in_layout
bool
label
object
linestyle or ls
{'-', '--', '-.', ':', '', (offset, on-off-seq), ...}
linewidth or lw
float
marker
marker style string, Path or MarkerStyle
markeredgecolor or mec
color
markeredgewidth or mew
float
markerfacecolor or mfc
color
markerfacecoloralt or mfcalt
color
markersize or ms
float
markevery
None or int or (int, int) or slice or list[int] or float or (float, float) or list[bool]
path_effects
AbstractPathEffect
picker
float or callable[[Artist, Event], tuple[bool, dict]]
pickradius
float
rasterized
bool
sketch_params
(scale: float, length: float, randomness: float)
snap
bool or None
solid_capstyle
CapStyle or {'butt', 'projecting', 'round'}
solid_joinstyle
JoinStyle or {'miter', 'round', 'bevel'}
transform
unknown
url
str
visible
bool
xdata
1D array
ydata
1D array
zorder
float
See also
Helper functions on dates.
Convert dates to num.
Convert num to dates.
Create an equally spaced sequence of dates.
If you are using custom date tickers and formatters, it may be necessary to set the formatters/locators after the call to plot_date. plot_date will set the default tick locator to AutoDateLocator (if the tick locator is not already set to a DateLocator instance) and the default tick formatter to AutoDateFormatter (if the tick formatter is not already set to a DateFormatter instance).


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


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


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


Efficiently redraw Axes data, but not axis ticks, labels, etc.
This method can only be used after an initial draw which caches the renderer.


Recompute the data limits based on current artists.
At present, Collection instances are not supported.
Whether to exclude invisible artists.
Packed-bubble chart
Textbox


Remove a callback based on its observer id.
See also


Reset the active position to the original position.
This resets the a possible position change due to aspect constraints. For an explanation of the positions see set_position.


A scatter plot of y vs. x with varying marker size and/or color.
The data positions.
The marker size in points**2. Default is rcParams['lines.markersize'] ** 2.
The marker colors. Possible values:
Note that c should not be a single numeric RGB or RGBA sequence because that is indistinguishable from an array of values to be colormapped. If you want to specify the same RGB or RGBA value for all points, use a 2D array with a single row. Otherwise, value- matching will have precedence in case of a size matching with x and y.
If you wish to specify a single color for all points prefer the color keyword argument.
Defaults to None. In that case the marker color is determined by the value of color, facecolor or facecolors. In case those are not specified or None, the marker color is determined by the next color of the Axes' current "shape and fill" color cycle. This cycle defaults to rcParams["axes.prop_cycle"] (default: cycler('color', ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf'])).
The marker style. marker can be either an instance of the class or the text shorthand for a particular marker. See matplotlib.markers for more information about marker styles.
A Colormap instance or registered colormap name. cmap is only used if c is an array of floats.
If c is an array of floats, norm is used to scale the color data, c, in the range 0 to 1, in order to map into the colormap cmap. If None, use the default colors.Normalize.
vmin and vmax are used in conjunction with the default norm to map the color array c to the colormap cmap. If None, the respective min and max of the color array is used. It is an error to use vmin/vmax when norm is given.
The alpha blending value, between 0 (transparent) and 1 (opaque).
The linewidth of the marker edges. Note: The default edgecolors is 'face'. You may want to change this as well.
The edge color of the marker. Possible values:
For non-filled markers, edgecolors is ignored. Instead, the color is determined like with 'face', i.e. from c, colors, or facecolors.
Whether to plot points with nonfinite c (i.e. inf, -inf or nan). If True the points are drawn with the bad colormap color (see Colormap.set_bad).
If given, the following parameters also accept a string s, which is interpreted as data[s] (unless this raises an exception):
x, y, s, linewidths, edgecolors, c, facecolor, facecolors, color
See also
To plot scatter plots when markers are identical in size and color.
Scatter Custom Symbol
Scatter Demo2
Scatter plot with histograms
Scatter plot with pie chart markers
Scatter plots with a legend
Advanced quiver and quiverkey functions
Axes box aspect
Axis Label Position
Plot a confidence ellipse of a two-dimensional dataset
Violin plot customization
Scatter plot on polar axis
Legend Demo
Scatter Histogram (Locatable Axes)
mpl_toolkits.axisartist.floating_axes features
Rain simulation
Zoom Window
Plotting with keywords
Zorder Demo
Plot 2D data on 3D plot
3D scatterplot
Automatically setting tick positions
Unit handling
Annotate Text Arrow
Polygon Selector
Basic Usage
Choosing Colormaps in Matplotlib
scatter(x, y)


Add a second x-axis to this Axes.
For example if we want to have a second scale for the data plotted on the xaxis.
The position to put the secondary axis. Strings can be 'top' or 'bottom' for orientation='x' and 'right' or 'left' for orientation='y'. A float indicates the relative position on the parent axes to put the new axes, 0.0 being the bottom (or left) and 1.0 being the top (or right).
If a 2-tuple of functions, the user specifies the transform function and its inverse. i.e. functions=(lambda x: 2 / x, lambda x: 2 / x) would be an reciprocal transform with a factor of 2.
The user can also directly supply a subclass of transforms.Transform so long as it has an inverse.
See Secondary Axis for examples of making these conversions.
Other miscellaneous axes parameters.
Warning
This method is experimental as of 3.1, and the API may change.
The main axis shows frequency, and the secondary axis shows period.
(Source code, png, pdf)
Secondary Axis
Basic Usage


Add a second y-axis to this Axes.
For example if we want to have a second scale for the data plotted on the yaxis.
The position to put the secondary axis. Strings can be 'top' or 'bottom' for orientation='x' and 'right' or 'left' for orientation='y'. A float indicates the relative position on the parent axes to put the new axes, 0.0 being the bottom (or left) and 1.0 being the top (or right).
If a 2-tuple of functions, the user specifies the transform function and its inverse. i.e. functions=(lambda x: 2 / x, lambda x: 2 / x) would be an reciprocal transform with a factor of 2.
The user can also directly supply a subclass of transforms.Transform so long as it has an inverse.
See Secondary Axis for examples of making these conversions.
Other miscellaneous axes parameters.
Warning
This method is experimental as of 3.1, and the API may change.
Add a secondary Axes that converts from radians to degrees
(Source code, png, pdf)
Secondary Axis


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


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


Set multiple properties at once.
Supported properties are
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
Curve with error band
Bar chart with gradients
Simple Plot
Creating a timeline with lines, dates, and text
Contour plot of irregularly spaced data
Streamplot
Axes Demo
Creating multiple subplots using plt.subplots
Boxplots
Hexagonal binned plot
Nested pie charts
Annotating Plots
Arrow Demo
Usetex Baseline Test
Text Commands
Drawing fancy boxes
Adding a colorbar to inset axes
Inset Locator Demo
Animated 3D random walk
Zoom Window
Manual Contour
Plotting with keywords
3D box surface plot
Projecting contour profiles onto a graph
Projecting filled contour onto a graph
Generate polygons to fill under 3D line graph
3D stem
3D voxel / volumetric plot with rgb colors
Log Demo
Annotate Explain
Connection styles for annotations
Nested GridSpecs
Simple Annotate01
Mouse Cursor
The Lifecycle of a Plot
Arranging multiple Axes in a Figure
plot(x, y)
scatter(x, y)
bar(x, height) / barh(y, width)
stem(x, y)
step(x, y)
fill_between(x, y1, y2)
barbs(X, Y, U, V)
quiver(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)


Set how the Axes adjusts to achieve the required aspect ratio.
If 'box', change the physical dimensions of the Axes. If 'datalim', change the x or y data limits.
If True, apply the settings to all shared Axes.
See also
For a description of aspect handling.
Shared Axes (of which twinned Axes are a special case) impose restrictions on how aspect ratios can be imposed. For twinned Axes, use 'datalim'. For Axes that share both x and y, use 'box'. Otherwise, either 'datalim' or 'box' may be used. These limitations are partly a requirement to avoid over-specification, and partly a result of the particular implementation we are currently using, in which the adjustments for aspect ratios are done sequentially and independently on each Axes as it is drawn.
Loglog Aspect


Define the anchor location.
The actual drawing area (active position) of the Axes may be smaller than the Bbox (original position) when a fixed aspect is required. The anchor defines where the drawing area will be located within the available space.
Either an (x, y) pair of relative coordinates (0 is left or bottom, 1 is right or top), 'C' (center), or a cardinal direction ('SW', southwest, is bottom left, etc.). str inputs are shorthands for (x, y) coordinates, as shown in the following table:
'NW' (0.0, 1.0)
'N' (0.5, 1.0)
'NE' (1.0, 1.0)
'W' (0.0, 0.5)
'C' (0.5, 0.5)
'E' (1.0, 0.5)
'SW' (0.0, 0.0)
'S' (0.5, 0.0)
'SE' (1.0, 0.0)
If True, apply the settings to all shared Axes.
See also
for a description of aspect handling.


Set the aspect ratio of the axes scaling, i.e. y/x-scale.
Possible values:
If not None, this defines which parameter will be adjusted to meet the required aspect. See set_adjustable for further details.
If not None, this defines where the Axes will be drawn if there is extra space due to aspect constraints. The most common way to to specify the anchor are abbreviations of cardinal directions:
value
description
'C'
centered
'SW'
lower left corner
'S'
middle of bottom edge
'SE'
lower right corner
etc.
See set_anchor for further details.
If True, apply the settings to all shared Axes.
See also
Set how the Axes adjusts to achieve the required aspect ratio.
Set the position in case of extra space.
Bar chart with gradients
Streamplot
Tricontour Demo
Tricontour Smooth Delaunay
Tricontour Smooth User
Trigradient Demo
Tripcolor Demo
Triplot Demo
Axes box aspect
Controlling view limits using margins and sticky_edges
Placing Colorbars
Multiline
Mmh Donuts!!!
Inset Locator Demo2
Scatter Histogram (Locatable Axes)
Simple Anchored Artists
axis_direction demo
Simple Axis Pad
The double pendulum problem
Anchored Artists
Rasterization for vector graphics
Loglog Aspect
Annotate Text Arrow
Transformations Tutorial
Colormap Normalization


Set whether autoscaling is applied to each axis on the next draw or call to Axes.autoscale_view.
Resampling Data


Set whether the x-axis is autoscaled on the next draw or call to Axes.autoscale_view.


Set whether the y-axis is autoscaled on the next draw or call to Axes.autoscale_view.


Turn the x- and y-axis off.
This affects the axis lines, ticks, ticklabels, grid and axis labels.
Marker reference
Barcode
Blend transparency with color in 2D images
Nested pie charts
Annotation arrow style reference
Precise text layout
Drawing fancy boxes
Choosing Colormaps in Matplotlib
Text properties and layout


Turn the x- and y-axis on.
This affects the axis lines, ticks, ticklabels, grid and axis labels.


Set whether axis ticks and gridlines are above or below most artists.
This controls the zorder of the ticks and gridlines. For more information on the zorder see Zorder Demo.
Possible values:
See also


Set the Axes box aspect, i.e. the ratio of height to width.
This defines the aspect of the Axes in figure space and is not to be confused with the data aspect (see set_aspect).
Changes the physical dimensions of the Axes, such that the ratio of the Axes height to the Axes width in physical units is equal to aspect. Defining a box aspect will change the adjustable property to 'datalim' (see set_adjustable).
None will disable a fixed box aspect so that height and width of the Axes are chosen independently.
See also
for a description of aspect handling.
Axes box aspect


Set the facecolor of the Axes.
Color Demo


Set whether the Axes rectangle patch is drawn.


Set whether the Axes responds to navigation toolbar commands.


Set the navigation toolbar button status.
Warning
this is not a user-API function.


Set the Axes position.
Axes have two position attributes. The 'original' position is the position allocated for the Axes. The 'active' position is the position the Axes is actually drawn at. These positions are usually the same unless a fixed aspect is set to the Axes. See Axes.set_aspect for details.
The new position of the in Figure coordinates.
Determines which position variables to change.
See also
Contour Demo


Set the property cycle of the Axes.
The property cycle controls the style properties such as color, marker and linestyle of future plot commands. The style properties of data already added to the Axes are not modified.
Call signatures:
Form 1 sets given Cycler object.
Form 2 creates a Cycler which cycles over one or more properties simultaneously and set it as the property cycle of the Axes. If multiple properties are given, their value lists must have the same length. This is just a shortcut for explicitly creating a cycler and passing it to the function, i.e. it's short for set_prop_cycle(cycler(label=values label2=values2, ...)).
Form 3 creates a Cycler for a single property and set it as the property cycle of the Axes. This form exists for compatibility with the original cycler.cycler interface. Its use is discouraged in favor of the kwarg form, i.e. set_prop_cycle(label=values).
Set the given Cycler. None resets to the cycle defined by the current style.
The property key. Must be a valid Artist property. For example, 'color' or 'linestyle'. Aliases are allowed, such as 'c' for 'color' and 'lw' for 'linewidth'.
Finite-length iterable of the property values. These values are validated and will raise a ValueError if invalid.
See also
Convenience function for creating validated cyclers for properties.
The original function for creating unvalidated cyclers.
Setting the property cycle for a single property:
Setting the property cycle for simultaneously cycling over multiple properties (e.g. red circle, green plus, blue cross):
Bachelor's degrees by gender
Styling with cycler


Set the zorder threshold for rasterization for vector graphics output.
All artists with a zorder below the given value will be rasterized if they support rasterization.
This setting is ignored for pixel-based output.
See also Rasterization for vector graphics.
The zorder below which artists are rasterized. If None rasterization based on zorder is deactivated.
Rasterization for vector graphics


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.
Text to use for the title
A dictionary controlling the appearance of the title text, the default fontdict is:
Which title to set.
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.
The offset of the title from the top of the Axes, in points.
The matplotlib text instance representing the title
Other keyword arguments are text properties, see Text for a list of valid text properties.
Bar Label Demo
Stacked bar chart
Grouped bar chart with labels
Horizontal bar chart
Errorbar subsampling
EventCollection Demo
Fill Between and Alpha
Filling the area between lines
Fill Betweenx Demo
Hat graph
Markevery Demo
Psd Demo
Scatter Demo2
Using span_where
Stackplots and streamgraphs
hlines and vlines
Contour Corner Mask
Contour Demo
Contour Label Demo
Contourf Demo
Creating annotated heatmaps
Image antialiasing
Image Demo
Image Masked
Image Nonuniform
Interpolations for imshow
Contour plot of irregularly spaced data
Pcolor Demo
pcolormesh grids and shading
pcolormesh
Streamplot
Advanced quiver and quiverkey functions
Tricontour Demo
Tricontour Smooth Delaunay
Tricontour Smooth User
Trigradient Demo
Tripcolor Demo
Triplot Demo
Axes Demo
Controlling view limits using margins and sticky_edges
Resizing axes with constrained layout
Resizing axes with tight layout
Figure labels: suptitle, supxlabel, supylabel
Invert Axes
Secondary Axis
Figure subfigures
Creating multiple subplots using plt.subplots
Box plots with custom fill colors
Plot a confidence ellipse of a two-dimensional dataset
Violin plot customization
Different ways of specifying error bars
Including upper and lower limits in error bars
Hexagonal binned plot
Using histograms to plot a cumulative distribution
Some features of the histogram (hist) function
The histogram (hist) function with multiple data sets
Bar of pie
Labeling a pie and a donut
Polar plot
Using accented text in matplotlib
Scale invariant angle label
Date tick labels
Custom tick formatter for time series
Labeling ticks using engineering notation
Using a ttf font file in Matplotlib
Labelling subplots
Legend Demo
Mathtext
Math fontfamily
Multiline
Rendering math equations using TeX
Title positioning
Boxplot Demo
Simple axes labels
Text Commands
Color Demo
Creating a colormap from a list of colors
Line, Poly and RegularPoly Collection with autoscaling
Compound path
Mmh Donuts!!!
Line Collection
Bezier Curve
Bayesian Methods for Hackers style sheet
Dark background style sheet
FiveThirtyEight style sheet
Make Room For Ylabel Using Axesgrid
Axis Direction
Anatomy of a figure
XKCD
pyplot animation
Data Browser
Image Slices Viewer
Keypress event
Lasso Demo
Legend Picking
Looking Glass
Path Editor
Pick Event Demo2
Poly Editor
Trifinder Event Demo
Viewlims
Cross hair cursor
Packed-bubble chart
Pythonic Matplotlib
Rasterization for vector graphics
Zorder Demo
Demo of 3D bar charts
Lorenz Attractor
3D wireframe plots in one direction
Loglog Aspect
Exploring normalizations
Scales
Radar chart (aka spider or star chart)
Topographic hillshading
Spine Placement
Spines
Dropped spines
Colorbar Tick Labelling
Date Precision and Epochs
Set default x-axis tick labels on the top
Artist tests
Group barchart with units
Evans test
Interactive Adjustment of Colormap Range
Annotated Cursor
Rectangle and ellipse selectors
Span Selector
Basic Usage
Image tutorial
Artist tutorial
Styling with cycler
Constrained Layout Guide
Tight Layout guide
Transformations Tutorial
Specifying Colors
Colormap Normalization
Text in Matplotlib Plots


Set the lower and upper numerical bounds of the x-axis.
This method will honor axis inversion regardless of parameter order. It will not change the autoscaling setting (get_autoscalex_on()).
The lower and upper bounds. If None, the respective axis bound is not modified.
See also


Set the label for the x-axis.
The label text.
Spacing in points from the Axes bounding box including ticks and tick labels. If None, the previous value is left as is.
The label position. This is a high-level alternative for passing parameters x and horizontalalignment.
Text properties control the appearance of the label.
See also
Documents the properties supported by Text.
Bar Label Demo
Horizontal bar chart
Broken Barh
CSD Demo
Fill Between and Alpha
Filling the area between lines
Fill Betweenx Demo
Hatch-filled histograms
Hat graph
Psd Demo
Scatter Demo2
Stackplots and streamgraphs
hlines and vlines
Contourf Demo
Tricontour Demo
Tripcolor Demo
Triplot Demo
Aligning Labels
Axes Demo
Axis Label Position
Resizing axes with constrained layout
Resizing axes with tight layout
Figure labels: suptitle, supxlabel, supylabel
Invert Axes
Secondary Axis
Figure subfigures
Multiple subplots
Plots with different scales
Box plots with custom fill colors
Boxplots
Box plot vs. violin plot comparison
Violin plot customization
Using histograms to plot a cumulative distribution
Some features of the histogram (hist) function
Producing multiple histograms side by side
Using accented text in matplotlib
Labeling ticks using engineering notation
Using a ttf font file in Matplotlib
Legend Demo
Mathtext
Multiline
Rendering math equations using TeX
Title positioning
Simple axes labels
Text Commands
Color Demo
Line, Poly and RegularPoly Collection with autoscaling
Ellipse Collection
Dark background style sheet
Make Room For Ylabel Using Axesgrid
Parasite Simple
Parasite Axes demo
Parasite axis demo
Ticklabel alignment
Simple Axis Direction03
Simple Axisline
Anatomy of a figure
XKCD
Keypress event
Pythonic Matplotlib
Plot 2D data on 3D plot
Create 2D bar graphs in different planes
3D errorbars
Lorenz Attractor
Automatic Text Offsetting
3D scatterplot
3D surface with polar coordinates
Text annotations in 3D
Log Bar
MRI With EEG
Multiple Yaxis With Spines
Centering labels between ticks
Pgf Fonts
Pgf Texsystem
Slider
Basic Usage
Artist tutorial
Constrained Layout Guide
Tight Layout guide
Arranging multiple Axes in a Figure
Choosing Colormaps in Matplotlib
Text in Matplotlib Plots


Set the x-axis view limits.
The left xlim in data coordinates. Passing None leaves the limit unchanged.
The left and right xlims may also be passed as the tuple (left, right) as the first positional argument (or as the left keyword argument).
The right xlim in data coordinates. Passing None leaves the limit unchanged.
Whether to notify observers of limit change.
Whether to turn on autoscaling of the x-axis. True turns on, False turns off, None leaves unchanged.
They are equivalent to left and right respectively, and it is an error to pass both xmin and left or xmax and right.
The new x-axis limits in data coordinates.
See also
The left value may be greater than the right value, in which case the x-axis values will decrease from left to right.
One limit may be left unchanged.
Limits may be passed in reverse order to flip the direction of the x-axis. For example, suppose x represents the number of years before present. The x-axis limits might be set like the following so 5000 years ago is on the left of the plot and the present is on the right.
Bar Label Demo
Broken Barh
CSD Demo
EventCollection Demo
Markevery Demo
Contouring the solution space of optimizations
Image Nonuniform
pcolormesh grids and shading
Axes box aspect
Axes Demo
Figure labels: suptitle, supxlabel, supylabel
Invert Axes
Zoom region inset axes
Boxplots
Violin plot customization
Including upper and lower limits in error bars
Bar of pie
AnnotationBbox demo
Using a text as a Path
Text Rotation Relative To Line
Annotate Transform
Mmh Donuts!!!
Ellipse Demo
Line Collection
Inset Locator Demo2
Parasite Simple2
axis_direction demo
Parasite Axes demo
Parasite axis demo
Simple Axis Pad
Anatomy of a figure
Bachelor's degrees by gender
XKCD
Decay
Rain simulation
Path Editor
Poly Editor
Resampling Data
Zoom Window
Frontpage contour example
Frontpage plot example
Custom projection
Building histograms using Rectangles and PolyCollections
SVG Filter Line
TickedStroke patheffect
Plot 2D data on 3D plot
Draw flat objects in 3D plot
Text annotations in 3D
Loglog Aspect
Scales
MRI With EEG
SkewT-logP diagram: using transforms and custom projections
Multiple Yaxis With Spines
Custom spine bounds
Formatting date ticks using ConciseDateFormatter
Date Demo Convert
Annotation with units
Artist tests
Annotate Text Arrow
Connect Simple01
Annotated Cursor
Cursor
Span Selector
Path Tutorial
Transformations Tutorial
Specifying Colors
Choosing Colormaps in Matplotlib


Set padding of X data limits prior to autoscaling.
m times the data interval will be added to each end of that interval before it is used in autoscaling. For example, if your data is in the range [0, 2], a factor of m = 0.1 will result in a range [-0.2, 2.2].
Negative values -0.5 < m < 0 will result in clipping of the data range. I.e. for a data range [0, 2], a factor of m = -0.1 will result in a range [0.2, 1.8].
Automatically setting tick positions


Set the x-axis scale.
The axis scale type to apply.
Different keyword arguments are accepted, depending on the scale. See the respective class keyword arguments:
By default, Matplotlib supports the above mentioned scales. Additionally, custom scales may be registered using matplotlib.scale.register_scale. These scales can then also be used here.
Markevery Demo
Labeling ticks using engineering notation
Inset Locator Demo
Loglog Aspect
Log Demo
Symlog Demo
Transformations Tutorial


Set the xaxis' labels with list of string labels.
Warning
This method should only be used after fixing the tick positions using Axes.set_xticks. Otherwise, the labels may end up in unexpected positions.
The label texts.
A dictionary controlling the appearance of the ticklabels. The default fontdict is:
Whether to set the minor ticklabels rather than the major ones.
The labels.
Managing multiple figures in pyplot
Zoom region inset axes
Boxplots
Rendering math equations using TeX
XKCD
Colorbar Tick Labelling
Constrained Layout Guide


Set the xaxis' tick locations and optionally labels.
If necessary, the view limits of the Axis are expanded so that all given ticks are visible.
List of tick locations.
List of tick labels. If not set, the labels show the data value.
If False, set the major ticks; if True, the minor ticks.
Text properties for the labels. These take effect only if you pass labels. In other cases, please use tick_params.
The mandatory expansion of the view limits is an intentional design choice to prevent the surprise of a non-visible tick. If you need other limits, you should set the limits explicitly after setting the ticks.
Bar Label Demo
Grouped bar chart with labels
Hat graph
Psd Demo
Creating annotated heatmaps
Box plot vs. violin plot comparison
Violin plot customization
Producing multiple histograms side by side
Multiline
Rendering math equations using TeX
ggplot style sheet
Scatter Histogram (Locatable Axes)
Simple Axisline4
Ticklabel alignment
Ticklabel direction
Bachelor's degrees by gender
Integral as the area under a curve
Shaded & power normalized rendering
XKCD
Rain simulation
MATPLOTLIB UNCHAINED
Frontpage 3D example
Frontpage contour example
Frontpage histogram example
Frontpage plot example
Log Bar
MRI With EEG
Custom spine bounds
Group barchart with units
The Lifecycle of a Plot


Set the lower and upper numerical bounds of the y-axis.
This method will honor axis inversion regardless of parameter order. It will not change the autoscaling setting (get_autoscaley_on()).
The lower and upper bounds. If None, the respective axis bound is not modified.
See also


Set the label for the y-axis.
The label text.
Spacing in points from the Axes bounding box including ticks and tick labels. If None, the previous value is left as is.
The label position. This is a high-level alternative for passing parameters y and horizontalalignment.
Text properties control the appearance of the label.
See also
Documents the properties supported by Text.
Bar Label Demo
Stacked bar chart
Grouped bar chart with labels
CSD Demo
Fill Between and Alpha
Hatch-filled histograms
Hat graph
Psd Demo
Scatter Demo2
Stackplots and streamgraphs
Contourf Demo
Creating annotated heatmaps
Tricontour Demo
Tripcolor Demo
Triplot Demo
Aligning Labels
Axes Demo
Axis Label Position
Resizing axes with constrained layout
Resizing axes with tight layout
Figure labels: suptitle, supxlabel, supylabel
Invert Axes
Secondary Axis
Figure subfigures
Multiple subplots
Plots with different scales
Box plots with custom fill colors
Boxplots
Box plot vs. violin plot comparison
Violin plot customization
Using histograms to plot a cumulative distribution
Some features of the histogram (hist) function
Producing multiple histograms side by side
Using accented text in matplotlib
Date tick labels
Legend Demo
Mathtext
Multiline
Rendering math equations using TeX
Simple axes labels
Text Commands
Color Demo
Line, Poly and RegularPoly Collection with autoscaling
Ellipse Collection
Dark background style sheet
Make Room For Ylabel Using Axesgrid
Parasite Simple
Parasite Axes demo
Parasite axis demo
Ticklabel alignment
Simple Axis Direction03
Simple Axisline
Anatomy of a figure
XKCD
Pythonic Matplotlib
Plot 2D data on 3D plot
Create 2D bar graphs in different planes
3D errorbars
Lorenz Attractor
2D and 3D Axes in same Figure
Automatic Text Offsetting
3D scatterplot
3D surface with polar coordinates
Text annotations in 3D
Log Bar
Symlog Demo
MRI With EEG
Topographic hillshading
Multiple Yaxis With Spines
Basic Usage
Artist tutorial
Constrained Layout Guide
Tight Layout guide
Arranging multiple Axes in a Figure
Choosing Colormaps in Matplotlib
Text in Matplotlib Plots


Set the y-axis view limits.
The bottom ylim in data coordinates. Passing None leaves the limit unchanged.
The bottom and top ylims may also be passed as the tuple (bottom, top) as the first positional argument (or as the bottom keyword argument).
The top ylim in data coordinates. Passing None leaves the limit unchanged.
Whether to notify observers of limit change.
Whether to turn on autoscaling of the y-axis. True turns on, False turns off, None leaves unchanged.
They are equivalent to bottom and top respectively, and it is an error to pass both ymin and bottom or ymax and top.
The new y-axis limits in data coordinates.
See also
The bottom value may be greater than the top value, in which case the y-axis values will decrease from bottom to top.
One limit may be left unchanged.
Limits may be passed in reverse order to flip the direction of the y-axis. For example, suppose y represents depth of the ocean in m. The y-axis limits might be set like the following so 5000 m depth is at the bottom of the plot and the surface, 0 m, is at the top.
Broken Barh
EventCollection Demo
Hat graph
Markevery Demo
Psd Demo
Contouring the solution space of optimizations
Image Nonuniform
pcolormesh grids and shading
Axes Demo
Broken Axis
Figure labels: suptitle, supxlabel, supylabel
Zoom region inset axes
Boxplots
AnnotationBbox demo
Using a text as a Path
Annotate Transform
Annotating a plot
Line, Poly and RegularPoly Collection with autoscaling
Mmh Donuts!!!
Ellipse Demo
Line Collection
Inset Locator Demo2
Parasite Simple2
axis_direction demo
Parasite Axes demo
Parasite axis demo
Simple Axis Pad
Simple Axisline
Anatomy of a figure
Bachelor's degrees by gender
Integral as the area under a curve
XKCD
Decay
Animated histogram
Rain simulation
MATPLOTLIB UNCHAINED
Data Browser
Path Editor
Pick Event Demo2
Poly Editor
Zoom Window
Frontpage contour example
Frontpage plot example
Custom projection
Building histograms using Rectangles and PolyCollections
Pythonic Matplotlib
SVG Filter Line
TickedStroke patheffect
Plot 2D data on 3D plot
Draw flat objects in 3D plot
Text annotations in 3D
Loglog Aspect
Log Demo
MRI With EEG
SkewT-logP diagram: using transforms and custom projections
Multiple Yaxis With Spines
Custom spine bounds
Annotation with units
Artist tests
Annotate Text Arrow
Connect Simple01
Annotated Cursor
Cursor
Span Selector
Basic Usage
Path Tutorial
Transformations Tutorial
Specifying Colors
Choosing Colormaps in Matplotlib


Set padding of Y data limits prior to autoscaling.
m times the data interval will be added to each end of that interval before it is used in autoscaling. For example, if your data is in the range [0, 2], a factor of m = 0.1 will result in a range [-0.2, 2.2].
Negative values -0.5 < m < 0 will result in clipping of the data range. I.e. for a data range [0, 2], a factor of m = -0.1 will result in a range [0.2, 1.8].


Set the y-axis scale.
The axis scale type to apply.
Different keyword arguments are accepted, depending on the scale. See the respective class keyword arguments:
By default, Matplotlib supports the above mentioned scales. Additionally, custom scales may be registered using matplotlib.scale.register_scale. These scales can then also be used here.
Markevery Demo
Artist customization in box plots
Boxplot drawer function
Different ways of specifying error bars
Loglog Aspect
Log Bar
Log Demo
Scales
Symlog Demo


Set the yaxis' labels with list of string labels.
Warning
This method should only be used after fixing the tick positions using Axes.set_yticks. Otherwise, the labels may end up in unexpected positions.
The label texts.
A dictionary controlling the appearance of the ticklabels. The default fontdict is:
Whether to set the minor ticklabels rather than the major ones.
The labels.
Zoom region inset axes
Artist customization in box plots
Boxplot drawer function
Violin plot basics
Rendering math equations using TeX
Colorbar Tick Labelling
Constrained Layout Guide


Set the yaxis' tick locations and optionally labels.
If necessary, the view limits of the Axis are expanded so that all given ticks are visible.
List of tick locations.
List of tick labels. If not set, the labels show the data value.
If False, set the major ticks; if True, the minor ticks.
Text properties for the labels. These take effect only if you pass labels. In other cases, please use tick_params.
The mandatory expansion of the view limits is an intentional design choice to prevent the surprise of a non-visible tick. If you need other limits, you should set the limits explicitly after setting the ticks.
Bar Label Demo
Horizontal bar chart
Broken Barh
Psd Demo
Creating annotated heatmaps
Rendering math equations using TeX
Programmatically controlling subplot adjustment
Make Room For Ylabel Using Axesgrid
Scatter Histogram (Locatable Axes)
Ticklabel alignment
Ticklabel direction
Bachelor's degrees by gender
Integral as the area under a curve
Shaded & power normalized rendering
XKCD
Rain simulation
MATPLOTLIB UNCHAINED
Frontpage 3D example
Frontpage contour example
Frontpage histogram example
Frontpage plot example
Create 2D bar graphs in different planes
MRI With EEG
SkewT-logP diagram: using transforms and custom projections
Custom spine bounds


Share the x-axis with other.
This is equivalent to passing sharex=other when constructing the axes, and cannot be used if the x-axis is already being shared with another Axes.


Share the y-axis with other.
This is equivalent to passing sharey=other when constructing the axes, and cannot be used if the y-axis is already being shared with another Axes.


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


Plot the sparsity pattern of a 2D array.
This visualizes the non-zero values of the array.
Two plotting styles are available: image and marker. Both are available for full arrays, but only the marker style works for scipy.sparse.spmatrix instances.
Image style
If marker and markersize are None, imshow is used. Any extra remaining keyword arguments are passed to this method.
Marker style
If Z is a scipy.sparse.spmatrix or marker or markersize are None, a Line2D object will be returned with the value of marker determining the marker type, and any remaining keyword arguments passed to plot.
The array to be plotted.
If precision is 0, any non-zero value will be plotted. Otherwise, values of \(|Z| > precision\) will be plotted.
For scipy.sparse.spmatrix instances, you can also pass 'present'. In this case any value present in the array will be plotted, even if it is identically zero.
The aspect ratio of the Axes. This parameter is particularly relevant for images since it determines whether data pixels are square.
This parameter is a shortcut for explicitly calling Axes.set_aspect. See there for further details.
Place the [0, 0] index of the array in the upper left or lower left corner of the Axes. The convention 'upper' is typically used for matrices and images.
The return type depends on the plotting style (see above).
The supported additional parameters depend on the plotting style.
For the image style, you can pass the following additional parameters of imshow:
For the marker style, you can pass any Line2D property except for linestyle:
Property
Description
agg_filter
a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha
scalar or None
animated
bool
antialiased or aa
bool
clip_box
Bbox
clip_on
bool
clip_path
Patch or (Path, Transform) or None
color or c
color
dash_capstyle
CapStyle or {'butt', 'projecting', 'round'}
dash_joinstyle
JoinStyle or {'miter', 'round', 'bevel'}
dashes
sequence of floats (on/off ink in points) or (None, None)
data
(2, N) array or two 1D arrays
drawstyle or ds
{'default', 'steps', 'steps-pre', 'steps-mid', 'steps-post'}, default: 'default'
figure
Figure
fillstyle
{'full', 'left', 'right', 'bottom', 'top', 'none'}
gid
str
in_layout
bool
label
object
linestyle or ls
{'-', '--', '-.', ':', '', (offset, on-off-seq), ...}
linewidth or lw
float
marker
marker style string, Path or MarkerStyle
markeredgecolor or mec
color
markeredgewidth or mew
float
markerfacecolor or mfc
color
markerfacecoloralt or mfcalt
color
markersize or ms
float
markevery
None or int or (int, int) or slice or list[int] or float or (float, float) or list[bool]
path_effects
AbstractPathEffect
picker
float or callable[[Artist, Event], tuple[bool, dict]]
pickradius
float
rasterized
bool
sketch_params
(scale: float, length: float, randomness: float)
snap
bool or None
solid_capstyle
CapStyle or {'butt', 'projecting', 'round'}
solid_joinstyle
JoinStyle or {'miter', 'round', 'bevel'}
transform
unknown
url
str
visible
bool
xdata
1D array
ydata
1D array
zorder
float
Spy Demos


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


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


Whether the artist is 'stale' and needs to be re-drawn for the output to match the internal state of the artist.


Called when a pan operation has started.
The mouse coordinates in display coords.
The pressed mouse button.
This is intended to be overridden by new projection types.


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


Make a step plot.
Call signatures:
This is just a thin wrapper around plot which changes some formatting options. Most of the concepts and parameters of plot can be used here as well.
Note
This method uses a standard plot with a step drawstyle: The x values are the reference positions and steps extend left/right/both directions depending on where.
For the common case where you know the values and edges of the steps, use stairs instead.
1D sequence of x positions. It is assumed, but not checked, that it is uniformly increasing.
1D sequence of y levels.
A format string, e.g. 'g' for a green line. See plot for a more detailed description.
Note: While full format strings are accepted, it is recommended to only specify the color. Line styles are currently ignored (use the keyword argument linestyle instead). Markers are accepted and plotted on the given positions, however, this is a rarely needed feature for step plots.
Define where the steps should be placed:
An object with labelled data. If given, provide the label names to plot in x and y.
Additional parameters are the same as those for plot.
Objects representing the plotted data.
step(x, y)


Draw streamlines of a vector flow.
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).
x and y-velocities. The number of rows and columns must match the length of y and x, respectively.
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).
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.
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.
Colormap used to plot streamlines and arrows. This is only used if color is an array.
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.
Scaling factor for the arrow size.
Arrow style specification. See FancyArrowPatch.
Minimum length of streamline in axes coordinates.
Coordinates of starting points for the streamlines in data coordinates (the same coordinates as the x and y arrays).
The zorder of the stream lines and arrows. Artists with lower zorder values are drawn first.
Maximum length of streamline in axes coordinates.
Integrate the streamline in forward, backward or both directions.
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
Container object with attributes
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.
Streamplot
streamplot(X, Y, U, V)


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.
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.
The background colors of the cells.
The alignment of the text within the cells.
The column widths in units of the axes. If not given, all columns will have a width of 1 / ncols.
The text of the row header cells.
The colors of the row header cells.
The text alignment of the row header cells.
The text of the column header cells.
The colors of the column header cells.
The text alignment of the column header cells.
The position of the cell with respect to ax. This must be one of the codes.
A bounding box to draw the table into. If this is not None, this overrides loc.
The cell edges to be drawn with a line. See also visible_edges.
The created table.
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


Add text to the Axes.
Add the text s to the Axes at location x, y in data coordinates.
The position to place the text. By default, this is in data coordinates. The coordinate system can be changed using the transform parameter.
The text.
A dictionary to override the default text properties. If fontdict is None, the defaults are determined by rcParams.
The created Text instance.
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
Individual keyword arguments can be used to override any given parameter:
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:
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:
Marker reference
BboxImage Demo
Creating annotated heatmaps
Boxplots
Bar of pie
Using accented text in matplotlib
Arrow Demo
Annotation arrow style reference
Labelling subplots
Mathtext
Math fontfamily
Multiline
Placing text boxes
Rendering math equations using TeX
Precise text layout
Text Rotation Relative To Line
Usetex Baseline Test
Text watermark
Text Commands
Drawing fancy boxes
Hatch style reference
Anatomy of a figure
Bachelor's degrees by gender
Integral as the area under a curve
Shaded & power normalized rendering
The double pendulum problem
MATPLOTLIB UNCHAINED
Data Browser
Pick Event Demo2
Cross hair cursor
Packed-bubble chart
Rasterization for vector graphics
Text annotations in 3D
Anscombe's quartet
Annotate Explain
Annotate Text Arrow
Connection styles for annotations
Custom box styles
Pgf Fonts
Pgf Texsystem
Simple Annotate01
Mouse Cursor
Basic Usage
The Lifecycle of a Plot
Artist tutorial
Arranging multiple Axes in a Figure
Path Tutorial
Transformations Tutorial
Specifying Colors
Choosing Colormaps in Matplotlib
Text in Matplotlib Plots
Text properties and layout


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.
The axis to which the parameters are applied.
The group of ticks to which the parameters are applied.
Whether to reset the ticks to defaults before updating them.
Puts ticks inside the axes, outside the axes, or both.
Tick length in points.
Tick width in points.
Tick color.
Distance in points between tick and label.
Tick label font size in points or as a string (e.g., 'large').
Tick label color.
Tick color and label color.
Tick and label zorder.
Whether to draw the respective ticks.
Whether to draw the respective tick labels.
Tick label rotation
Gridline color.
Transparency of gridlines: 0 (transparent) to 1 (opaque).
Width of gridlines in points.
Any valid Line2D line style spec.
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.
Scatter plot with histograms
Creating annotated heatmaps
Axes Props
Broken Axis
Plots with different scales
Polar Legend
Color Demo
Inset Locator Demo
Inset Locator Demo2
Make Room For Ylabel Using Axesgrid
Simple Axes Divider 3
Anatomy of a figure
Bachelor's degrees by gender
Anscombe's quartet
Multiple Yaxis With Spines
Major and minor ticks
Text in Matplotlib Plots


Configure the ScalarFormatter used by default for linear axes.
If a parameter is not set, the corresponding property of the formatter is left unchanged.
The axis to configure. Only major ticks are affected.
Whether to use scientific notation. The formatter default is to use scientific notation.
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]).
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).
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).
Render the offset and scientific notation in mathtext. The formatter default is rcParams["axes.formatter.use_mathtext"] (default: False).
If the current formatter is not a ScalarFormatter.
The default tick formatter


Draw contour lines on an unstructured triangular grid.
The triangulation can be specified in one of two ways; either
where triangulation is a Triangulation object, or
in which case a Triangulation object will be created. See that class' docstring for an explanation of these cases.
The remaining arguments may be:
where Z is the array of values to contour, one per point in the triangulation. The level values are chosen automatically.
contour up to levels+1 automatically chosen contour levels (levels intervals).
draw contour lines at the values specified in sequence levels, which must be in increasing order.
Use keyword arguments to control colors, linewidth, origin, cmap ... see below for more details.
The unstructured triangular grid.
If specified, then x, y, triangles, and mask are not accepted.
The coordinates of the values in Z.
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.
Which triangles are masked out.
The height values over which the contour is drawn.
Determines the number and positions of the contour lines / regions.
If an int n, use MaxNLocator, which tries to automatically choose no more than n+1 "nice" contour levels between vmin and vmax.
If array-like, draw contour lines at the specified levels. The values must be in increasing order.
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.
The alpha blending value, between 0 (transparent) and 1 (opaque).
A Colormap instance or registered colormap name. The colormap maps the level values to colors.
If both colors and cmap are given, an error is raised.
If a colormap is used, the Normalize instance scales the level values to the canonical colormap range [0, 1] for mapping to colors. If not given, the default linear scaling is used.
If not None, either or both of these values will be supplied to the Normalize instance, overriding the default color scaling based on levels.
Determines the orientation and exact position of Z by specifying the position of Z[0, 0]. This is only relevant, if X, Y are not given.
If origin is not None, then extent is interpreted as in imshow: it gives the outer pixel boundaries. In this case, the position of Z[0, 0] is the center of the pixel, not a corner. If origin is None, then (x0, y0) is the position of Z[0, 0], and (x1, y1) is the position of Z[-1, -1].
This argument is ignored if X and Y are specified in the call to contour.
The locator is used to determine the contour levels if they are not given explicitly via levels. Defaults to MaxNLocator.
Determines the 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().
Override axis units by specifying an instance of a matplotlib.units.ConversionInterface.
Enable antialiasing, overriding the defaults. For filled contours, the default is True. For line contours, it is taken from rcParams["lines.antialiased"] (default: True).
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).
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.
Contour plot of irregularly spaced data
Tricontour Demo
Tricontour Smooth Delaunay
Tricontour Smooth User
Trigradient Demo
Triangular 3D contour plot
tricontour(x, y, z)


Draw contour regions on an unstructured triangular grid.
The triangulation can be specified in one of two ways; either
where triangulation is a Triangulation object, or
in which case a Triangulation object will be created. See that class' docstring for an explanation of these cases.
The remaining arguments may be:
where Z is the array of values to contour, one per point in the triangulation. The level values are chosen automatically.
contour up to levels+1 automatically chosen contour levels (levels intervals).
draw contour regions at the values specified in sequence levels, which must be in increasing order.
Use keyword arguments to control colors, linewidth, origin, cmap ... see below for more details.
The unstructured triangular grid.
If specified, then x, y, triangles, and mask are not accepted.
The coordinates of the values in Z.
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.
Which triangles are masked out.
The height values over which the contour is drawn.
Determines the number and positions of the contour lines / regions.
If an int n, use MaxNLocator, which tries to automatically choose no more than n+1 "nice" contour levels between vmin and vmax.
If array-like, draw contour lines at the specified levels. The values must be in increasing order.
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.
The alpha blending value, between 0 (transparent) and 1 (opaque).
A Colormap instance or registered colormap name. The colormap maps the level values to colors.
If both colors and cmap are given, an error is raised.
If a colormap is used, the Normalize instance scales the level values to the canonical colormap range [0, 1] for mapping to colors. If not given, the default linear scaling is used.
If not None, either or both of these values will be supplied to the Normalize instance, overriding the default color scaling based on levels.
Determines the orientation and exact position of Z by specifying the position of Z[0, 0]. This is only relevant, if X, Y are not given.
If origin is not None, then extent is interpreted as in imshow: it gives the outer pixel boundaries. In this case, the position of Z[0, 0] is the center of the pixel, not a corner. If origin is None, then (x0, y0) is the position of Z[0, 0], and (x1, y1) is the position of Z[-1, -1].
This argument is ignored if X and Y are specified in the call to contour.
The locator is used to determine the contour levels if they are not given explicitly via levels. Defaults to MaxNLocator.
Determines the 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().
Override axis units by specifying an instance of a matplotlib.units.ConversionInterface.
Enable antialiasing, overriding the defaults. For filled contours, the default is True. For line contours, it is taken from rcParams["lines.antialiased"] (default: True).
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.
tricontourf fills intervals that are closed at the top; that is, for boundaries z1 and z2, the filled region is:
except for the lowest interval, which is closed on both sides (i.e. it includes the lowest value).
Contour plot of irregularly spaced data
Tricontour Demo
Tricontour Smooth User
Triangular 3D filled contour plot
tricontourf(x, y, z)


Create a pseudocolor plot of an unstructured triangular grid.
The triangulation can be specified in one of two ways; either:
where triangulation is a Triangulation object, or
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.
Tripcolor Demo
tripcolor(x, y, z)


Draw a unstructured triangular grid as lines and/or markers.
The triangulation to plot can be specified in one of two ways; either:
where triangulation is a Triangulation object, or
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.
The drawn triangles edges.
The drawn marker nodes.
Tricontour Smooth Delaunay
Tricontour Smooth User
Trigradient Demo
Triplot Demo
Trifinder Event Demo
triplot(x, y)


Create a twin Axes sharing the xaxis.
Create a new Axes with an invisible x-axis and an independent y-axis positioned opposite to the original one (i.e. at right). The x-axis autoscale setting will be inherited from the original Axes. To ensure that the tick marks of both y-axes align, see LinearLocator.
The newly created Axes instance
For those who are 'picking' artists while using twinx, pick events are only called for the artists in the top-most Axes.
Axes box aspect
Plots with different scales
Parasite Simple
Parasite axis demo
Multiple Yaxis With Spines
Basic Usage


Create a twin Axes sharing the yaxis.
Create a new Axes with an invisible y-axis and an independent x-axis positioned opposite to the original one (i.e. at top). The y-axis autoscale setting will be inherited from the original Axes. To ensure that the tick marks of both x-axes align, see LinearLocator.
The newly created Axes instance
For those who are 'picking' artists while using twiny, pick events are only called for the artists in the top-most Axes.


Extend the dataLim Bbox to include the given points.
If no data is set currently, the Bbox will ignore its limits and set the bound to be the bounds of the xydata (xys). Otherwise, it will compute the bounds of the union of its current data and the data in xys.
The points to include in the data limits Bbox. This can be either a list of (x, y) tuples or a Nx2 array.
Whether to update the x/y limits.


When autoscaling, whether to obey all Artist.sticky_edges.
Default is True.
Setting this to False ensures that the specified margins will be applied, even if the plot includes an image, for example, which would otherwise force a view limit to coincide with its data limit.
The changing this property does not change the plot until autoscale or autoscale_view is called.


Drawing function for violin plots.
Draw a violin plot for each column of vpstats. Each filled area extends to represent the entire data range, with optional lines at the mean, the median, the minimum, the maximum, and the quantiles values.
A list of dictionaries containing stats for each violin plot. Required keys are:
Optional keys are:
The positions of the violins. The ticks and limits are automatically set to match the positions.
If true, plots the violins vertically. Otherwise, plots the violins horizontally.
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.
If true, will toggle rendering of the means.
If true, will toggle rendering of the extrema.
If true, will toggle rendering of the medians.
A dictionary mapping each component of the violinplot to a list of the corresponding collection instances created. The dictionary has the following keys: