This tutorial covers some basic usage patterns and best practices to
help you get started with Matplotlib.
importmatplotlib.pyplotaspltimportnumpyasnp
A simple example
Matplotlib graphs your data on Figures (e.g., windows, Jupyter
widgets, etc.), each of which can contain one or more , an
area where points can be specified in terms of x-y coordinates (or theta-r
in a polar plot, x-y-z in a 3D plot, etc.). The simplest way of
creating a Figure with an Axes is using . We can then use
to draw some data on the Axes, and to display
the figure:
fig,ax=plt.subplots()# Create a figure containing a single Axes.ax.plot([1,2,3,4],[1,4,2,3])# Plot some data on the Axes.plt.show()# Show the figure.
Depending on the environment you are working in, plt.show() can be left
out. This is for example the case with Jupyter notebooks, which
automatically show all figures created in a code cell.
The whole figure. The Figure keeps
track of all the child Axes, a group of
'special' Artists (titles, figure legends, colorbars, etc.), and
even nested subfigures.
Typically, you'll create a new Figure through one of the following
functions:
fig=plt.figure()# an empty figure with no Axesfig,ax=plt.subplots()# a figure with a single Axesfig,axs=plt.subplots(2,2)# a figure with a 2x2 grid of Axes# a figure with one Axes on the left, and two on the right:fig,axs=plt.subplot_mosaic([['left','right_top'],['left','right_bottom']])
subplots() and subplot_mosaic are convenience functions
that additionally create Axes objects inside the Figure, but you can also
manually add Axes later on.
An Axes is an Artist attached to a Figure that contains a region for
plotting data, and usually includes two (or three in the case of 3D)
Axis objects (be aware of the difference
between Axes and Axis) that provide ticks and tick labels to
provide scales for the data in the Axes. Each Axes also
has a title
(set via set_title()), an x-label (set via
set_xlabel()), and a y-label set via
).
These objects set the scale and limits and generate ticks (the marks
on the Axis) and ticklabels (strings labeling the ticks). The location
of the ticks is determined by a Locator object and the
ticklabel strings are formatted by a Formatter. The
combination of the correct Locator and Formatter gives very fine
control over the tick locations and labels.
Basically, everything visible on the Figure is an Artist (even
Figure, Axes, and Axis objects). This includes
Text objects, objects, objects,
objects, etc. When the Figure is rendered, all of the
Artists are drawn to the . Most Artists are tied to an Axes; such
an Artist cannot be shared by multiple Axes, or moved from one to another.
Types of inputs to plotting functions
Plotting functions expect numpy.array or numpy.ma.masked_array as
input, or objects that can be passed to numpy.asarray.
Classes that are similar to arrays ('array-like') such as pandas
data objects and numpy.matrix may not work as intended. Common convention
is to convert these to numpy.array objects prior to plotting.
For example, to convert a numpy.matrix
b=np.matrix([[1,2],[3,4]])b_asarray=np.asarray(b)
Most methods will also parse a string-indexable object like a dict, a
structured numpy array, or a pandas.DataFrame. Matplotlib allows you
to provide the data keyword argument and generate plots passing the
strings corresponding to the x and y variables.
x=np.linspace(0,2,100)# Sample data.# Note that even in the OO-style, we use `.pyplot.figure` to create the Figure.fig,ax=plt.subplots(figsize=(5,2.7),layout='constrained')ax.plot(x,x,label='linear')# Plot some data on the Axes.ax.plot(x,x**2,label='quadratic')# Plot more data on the Axes...ax.plot(x,x**3,label='cubic')# ... and some more.ax.set_xlabel('x label')# Add an x-label to the Axes.ax.set_ylabel('y label')# Add a y-label to the Axes.ax.set_title("Simple Plot")# Add a title to the Axes.ax.legend()# Add a legend.
(In addition, there is a third approach, for the case when embedding
Matplotlib in a GUI application, which completely drops pyplot, even for
figure creation. See the corresponding section in the gallery for more info:
Embedding Matplotlib in graphical user interfaces.)
Matplotlib's documentation and examples use both the OO and the pyplot
styles. In general, we suggest using the OO style, particularly for
complicated plots, and functions and scripts that are intended to be reused
as part of a larger project. However, the pyplot style can be very convenient
for quick interactive work.
Making a helper functions
If you need to make the same plots over and over again with different data
sets, or want to easily wrap Matplotlib methods, use the recommended
signature function below.
defmy_plotter(ax,data1,data2,param_dict):""" A helper function to make a graph. """out=
Styling Artists
Most plotting methods have styling options for the Artists, accessible either
when a plotting method is called, or from a "setter" on the Artist. In the
plot below we manually set the color, linewidth, and linestyle of the
Artists created by plot, and we set the linestyle of the second line
after the fact with set_linestyle.
Matplotlib has a very flexible array of colors that are accepted for most
Artists; see allowable color definitions for a
list of specifications. Some Artists will take multiple colors. i.e. for
a scatter plot, the edge of the markers can be different colors
from the interior:
Line widths are typically in typographic points (1 pt = 1/72 inch) and
available for Artists that have stroked lines. Similarly, stroked lines
can have a linestyle. See the linestyles example.
Marker size depends on the method being used. plot specifies
markersize in points, and is generally the "diameter" or width of the
marker. scatter specifies markersize as approximately
proportional to the visual area of the marker. There is an array of
markerstyles available as string codes (see markers), or
users can define their own MarkerStyle (see
):
All of the text functions return a matplotlib.text.Text
instance. Just as with lines above, you can customize the properties by
passing keyword arguments into the text functions:
Matplotlib accepts TeX equation expressions in any text expression.
For example to write the expression σi=15 in the title,
you can write a TeX expression surrounded by dollar signs:
Each Axes has two (or three) Axis objects representing the x- and
y-axis. These control the scale of the Axis, the tick locators and the
tick formatters. Additional Axes can be attached to display further Axis
objects.
Scales
In addition to the linear scale, Matplotlib supplies non-linear scales,
such as a log-scale. Since log-scales are used so much there are also
direct methods like loglog, semilogx, and
semilogy. There are a number of scales (see
Scales overview for other examples). Here we set the scale
manually:
The scale sets the mapping from data values to spacing along the Axis. This
happens in both directions, and gets combined into a transform, which
is the way that Matplotlib maps from data coordinates to Axes, Figure, or
screen coordinates. See Transformations Tutorial.
Tick locators and formatters
Each Axis has a tick locator and formatter that choose where along the
Axis objects to put tick marks. A simple interface to this is
set_xticks:
Matplotlib can handle plotting arrays of dates and arrays of strings, as
well as floating point numbers. These get special locators and formatters
as appropriate. For dates:
Plotting data of different magnitude in one chart may require
an additional y-axis. Such an Axis can be created by using
twinx to add a new Axes with an invisible x-axis and a y-axis
positioned at the right (analogously for twiny). See
Plots with different scales for another example.
Similarly, you can add a secondary_xaxis or
secondary_yaxis having a different scale than the main Axis to
represent the data in different scales or units. See
for further
examples.
Color mapped data
Often we want to have a third dimension in a plot represented by colors in
a colormap. Matplotlib has a number of plot types that do this:
Sometimes we want a non-linear mapping of the data to the colormap, as
in the LogNorm example above. We do this by supplying the
ScalarMappable with the norm argument instead of vmin and vmax.
More normalizations are shown at Colormap normalization.
Colorbars
Adding a colorbar gives a key to relate the color back to the
underlying data. Colorbars are figure-level Artists, and are attached to
a ScalarMappable (where they get their information about the norm and
colormap) and usually steal space from a parent Axes. Placement of
colorbars can be complex: see
Placing colorbars for
details. You can also change the appearance of colorbars with the
extend keyword to add arrows to the ends, and shrink and aspect to
control the size. Finally, the colorbar will have default locators
and formatters appropriate to the norm. These can be changed as for
other Axis objects.
Working with multiple Figures and Axes
You can open multiple Figures with multiple calls to
fig=plt.figure() or fig2,ax=plt.subplots(). By keeping the
object references you can add Artists to either Figure.
Multiple Axes can be added a number of ways, but the most basic is
plt.subplots() as used above. One can achieve more complex layouts,
with Axes objects spanning columns or rows, using subplot_mosaic.
The Axes methods are the primary interface for configuring
most parts of your plot (adding data, controlling axis scales and
limits, adding labels etc.).
Note that if you want to install these as a python package, or any other
customizations you could use one of the many templates on the web;
Matplotlib has one at mpl-cookiecutter
where the r preceding the title string signifies that the string is a
raw string and not to treat backslashes as python escapes.
Matplotlib has a built-in TeX expression parser and
layout engine, and ships its own math fonts – for details see
Writing mathematical expressions. You can also use LaTeX directly to format
your text and incorporate the output directly into your display figures or
saved postscript – see Text rendering with LaTeX.
In this basic example, both xy and xytext are in data coordinates.
There are a variety of other coordinate systems one can choose -- see
Basic annotation and Advanced annotation for
details. More examples also can be found in
Annotate plots.
Different scales can have different locators and formatters; for instance
the log-scale above uses LogLocator and LogFormatter. See
Tick locators and
Tick formatters for other formatters and
locators and information for writing your own.
One caveat about categorical plotting is that some methods of parsing
text files return a list of strings, even if the strings all represent
numbers or dates. If you pass 1000 strings, Matplotlib will think you
meant 1000 categories and will add 1000 ticks to your plot!