Note
Go to the endto download the full example code.
Quick start guide#
This tutorial covers some basic usage patterns and best practices tohelp you get started with Matplotlib.
importmatplotlib.pyplotaspltimportnumpyasnp
A simple example#
Matplotlib graphs your data onFigure
s (e.g., windows, Jupyterwidgets, etc.), each of which can contain one or moreAxes
, anarea where points can be specified in terms of x-y coordinates (or theta-rin a polar plot, x-y-z in a 3D plot, etc.). The simplest way ofcreating a Figure with an Axes is usingpyplot.subplots
. We can then useAxes.plot
to draw some data on the Axes, andshow
to displaythe 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 leftout. This is for example the case with Jupyter notebooks, whichautomatically show all figures created in a code cell.
Parts of a Figure#
Here are the components of a Matplotlib Figure.

Figure
#
Thewhole figure. The Figure keepstrack of all the childAxes
, a group of'special' Artists (titles, figure legends, colorbars, etc.), andeven nested subfigures.
Typically, you'll create a new Figure through one of the followingfunctions:
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()
andsubplot_mosaic
are convenience functionsthat additionally create Axes objects inside the Figure, but you can alsomanually add Axes later on.
For more on Figures, including panning and zooming, seeIntroduction to Figures.
Axes
#
An Axes is an Artist attached to a Figure that contains a region forplotting data, and usually includes two (or three in the case of 3D)Axis
objects (be aware of the differencebetweenAxes andAxis) that provide ticks and tick labels toprovide scales for the data in the Axes. EachAxes
alsohas a title(set viaset_title()
), an x-label (set viaset_xlabel()
), and a y-label set viaset_ylabel()
).
TheAxes
methods are the primary interface for configuringmost parts of your plot (adding data, controlling axis scales andlimits, adding labels etc.).
Axis
#
These objects set the scale and limits and generate ticks (the markson the Axis) and ticklabels (strings labeling the ticks). The locationof the ticks is determined by aLocator
object and theticklabel strings are formatted by aFormatter
. Thecombination of the correctLocator
andFormatter
gives very finecontrol over the tick locations and labels.
Artist
#
Basically, everything visible on the Figure is an Artist (evenFigure
,Axes
, andAxis
objects). This includesText
objects,Line2D
objects,collections
objects,Patch
objects, etc. When the Figure is rendered, all of theArtists are drawn to thecanvas. Most Artists are tied to an Axes; suchan Artist cannot be shared by multiple Axes, or moved from one to another.
Types of inputs to plotting functions#
Plotting functions expectnumpy.array
ornumpy.ma.masked_array
asinput, or objects that can be passed tonumpy.asarray
.Classes that are similar to arrays ('array-like') such aspandas
data objects andnumpy.matrix
may not work as intended. Common conventionis to convert these tonumpy.array
objects prior to plotting.For example, to convert anumpy.matrix
b=np.matrix([[1,2],[3,4]])b_asarray=np.asarray(b)
Most methods will also parse a string-indexable object like adict, astructured numpy array, or apandas.DataFrame
. Matplotlib allows youto provide thedata
keyword argument and generate plots passing thestrings corresponding to thex andy variables.
np.random.seed(19680801)# seed the random number generator.data={'a':np.arange(50),'c':np.random.randint(0,50,50),'d':np.random.randn(50)}data['b']=data['a']+10*np.random.randn(50)data['d']=np.abs(data['d'])*100fig,ax=plt.subplots(figsize=(5,2.7),layout='constrained')ax.scatter('a','b',c='c',s='d',data=data)ax.set_xlabel('entry a')ax.set_ylabel('entry b')

Coding styles#
The explicit and the implicit interfaces#
As noted above, there are essentially two ways to use Matplotlib:
Explicitly create Figures and Axes, and call methods on them (the"object-oriented (OO) style").
Rely on pyplot to implicitly create and manage the Figures and Axes, anduse pyplot functions for plotting.
SeeMatplotlib Application Interfaces (APIs) for an explanation of the tradeoffs between theimplicit and explicit interfaces.
So one can use the OO-style
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.

or the pyplot-style:
x=np.linspace(0,2,100)# Sample data.plt.figure(figsize=(5,2.7),layout='constrained')plt.plot(x,x,label='linear')# Plot some data on the (implicit) Axes.plt.plot(x,x**2,label='quadratic')# etc.plt.plot(x,x**3,label='cubic')plt.xlabel('x label')plt.ylabel('y label')plt.title("Simple Plot")plt.legend()

(In addition, there is a third approach, for the case when embeddingMatplotlib in a GUI application, which completely drops pyplot, even forfigure 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 pyplotstyles. In general, we suggest using the OO style, particularly forcomplicated plots, and functions and scripts that are intended to be reusedas part of a larger project. However, the pyplot style can be very convenientfor quick interactive work.
Note
You may find older examples that use thepylab
interface,viafrompylabimport*
. This approach is strongly deprecated.
Making a helper functions#
If you need to make the same plots over and over again with different datasets, or want to easily wrap Matplotlib methods, use the recommendedsignature function below.
which you would then use twice to populate two subplots:

Note that if you want to install these as a python package, or any othercustomizations you could use one of the many templates on the web;Matplotlib has one atmpl-cookiecutter
Styling Artists#
Most plotting methods have styling options for the Artists, accessible eitherwhen a plotting method is called, or from a "setter" on the Artist. In theplot below we manually set thecolor,linewidth, andlinestyle of theArtists created byplot
, and we set the linestyle of the second lineafter the fact withset_linestyle
.

Colors#
Matplotlib has a very flexible array of colors that are accepted for mostArtists; seeallowable color definitions for alist of specifications. Some Artists will take multiple colors. i.e. forascatter
plot, the edge of the markers can be different colorsfrom the interior:
fig,ax=plt.subplots(figsize=(5,2.7))ax.scatter(data1,data2,s=50,facecolor='C0',edgecolor='k')

Linewidths, linestyles, and markersizes#
Line widths are typically in typographic points (1 pt = 1/72 inch) andavailable for Artists that have stroked lines. Similarly, stroked linescan have a linestyle. See thelinestyles example.
Marker size depends on the method being used.plot
specifiesmarkersize in points, and is generally the "diameter" or width of themarker.scatter
specifies markersize as approximatelyproportional to the visual area of the marker. There is an array ofmarkerstyles available as string codes (seemarkers
), orusers can define their ownMarkerStyle
(seeMarker reference):

Labelling plots#
Axes labels and text#
set_xlabel
,set_ylabel
, andset_title
are used toadd text in the indicated locations (seeText in Matplotlibfor more discussion). Text can also be directly added to plots usingtext
:
mu,sigma=115,15x=mu+sigma*np.random.randn(10000)fig,ax=plt.subplots(figsize=(5,2.7),layout='constrained')# the histogram of the datan,bins,patches=ax.hist(x,50,density=True,facecolor='C0',alpha=0.75)ax.set_xlabel('Length [cm]')ax.set_ylabel('Probability')ax.set_title('Aardvark lengths\n (not really)')ax.text(75,.025,r'$\mu=115,\ \sigma=15$')ax.axis([55,175,0,0.03])ax.grid(True)

All of thetext
functions return amatplotlib.text.Text
instance. Just as with lines above, you can customize the properties bypassing keyword arguments into the text functions:
t=ax.set_xlabel('my data',fontsize=14,color='red')
These properties are covered in more detail inText properties and layout.
Using mathematical expressions in text#
Matplotlib accepts TeX equation expressions in any text expression.For example to write the expression\(\sigma_i=15\) in the title,you can write a TeX expression surrounded by dollar signs:
ax.set_title(r'$\sigma_i=15$')
where ther
preceding the title string signifies that the string is araw string and not to treat backslashes as python escapes.Matplotlib has a built-in TeX expression parser andlayout engine, and ships its own math fonts – for details seeWriting mathematical expressions. You can also use LaTeX directly to formatyour text and incorporate the output directly into your display figures orsaved postscript – seeText rendering with LaTeX.
Annotations#
We can also annotate points on a plot, often by connecting an arrow pointingtoxy, to a piece of text atxytext:
fig,ax=plt.subplots(figsize=(5,2.7))t=np.arange(0.0,5.0,0.01)s=np.cos(2*np.pi*t)line,=ax.plot(t,s,lw=2)ax.annotate('local max',xy=(2,1),xytext=(3,1.5),arrowprops=dict(facecolor='black',shrink=0.05))ax.set_ylim(-2,2)

In this basic example, bothxy andxytext are in data coordinates.There are a variety of other coordinate systems one can choose -- seeBasic annotation andAdvanced annotation fordetails. More examples also can be found inAnnotate plots.
Legends#
Often we want to identify lines or markers with aAxes.legend
:

Legends in Matplotlib are quite flexible in layout, placement, and whatArtists they can represent. They are discussed in detail inLegend guide.
Axis scales and ticks#
Each Axes has two (or three)Axis
objects representing the x- andy-axis. These control thescale of the Axis, the ticklocators and thetickformatters. Additional Axes can be attached to display further Axisobjects.
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 alsodirect methods likeloglog
,semilogx
, andsemilogy
. There are a number of scales (seeScales overview for other examples). Here we set the scalemanually:

The scale sets the mapping from data values to spacing along the Axis. Thishappens in both directions, and gets combined into atransform, whichis the way that Matplotlib maps from data coordinates to Axes, Figure, orscreen coordinates. SeeTransformations Tutorial.
Tick locators and formatters#
Each Axis has a ticklocator andformatter that choose where along theAxis objects to put tick marks. A simple interface to this isset_xticks
:
fig,axs=plt.subplots(2,1,layout='constrained')axs[0].plot(xdata,data1)axs[0].set_title('Automatic ticks')axs[1].plot(xdata,data1)axs[1].set_xticks(np.arange(0,100,30),['zero','30','sixty','90'])axs[1].set_yticks([-1.5,0,1.5])# note that we don't need to specify labelsaxs[1].set_title('Manual ticks')

Different scales can have different locators and formatters; for instancethe log-scale above usesLogLocator
andLogFormatter
. SeeTick locators andTick formatters for other formatters andlocators and information for writing your own.
Plotting dates and strings#
Matplotlib can handle plotting arrays of dates and arrays of strings, aswell as floating point numbers. These get special locators and formattersas appropriate. For dates:
frommatplotlib.datesimportConciseDateFormatterfig,ax=plt.subplots(figsize=(5,2.7),layout='constrained')dates=np.arange(np.datetime64('2021-11-15'),np.datetime64('2021-12-25'),np.timedelta64(1,'h'))data=np.cumsum(np.random.randn(len(dates)))ax.plot(dates,data)ax.xaxis.set_major_formatter(ConciseDateFormatter(ax.xaxis.get_major_locator()))

For more information see the date examples(e.g.Date tick labels)
For strings, we get categorical plotting (see:Plotting categorical variables).
fig,ax=plt.subplots(figsize=(5,2.7),layout='constrained')categories=['turnips','rutabaga','cucumber','pumpkins']ax.bar(categories,np.random.rand(len(categories)))

One caveat about categorical plotting is that some methods of parsingtext files return a list of strings, even if the strings all representnumbers or dates. If you pass 1000 strings, Matplotlib will think youmeant 1000 categories and will add 1000 ticks to your plot!
Additional Axis objects#
Plotting data of different magnitude in one chart may requirean additional y-axis. Such an Axis can be created by usingtwinx
to add a new Axes with an invisible x-axis and a y-axispositioned at the right (analogously fortwiny
). SeePlots with different scales for another example.
Similarly, you can add asecondary_xaxis
orsecondary_yaxis
having a different scale than the main Axis torepresent the data in different scales or units. SeeSecondary Axis for furtherexamples.
fig,(ax1,ax3)=plt.subplots(1,2,figsize=(7,2.7),layout='constrained')l1,=ax1.plot(t,s)ax2=ax1.twinx()l2,=ax2.plot(t,range(len(t)),'C1')ax2.legend([l1,l2],['Sine (left)','Straight (right)'])ax3.plot(t,s)ax3.set_xlabel('Angle [rad]')ax4=ax3.secondary_xaxis('top',(np.rad2deg,np.deg2rad))ax4.set_xlabel('Angle [°]')

Color mapped data#
Often we want to have a third dimension in a plot represented by colors ina colormap. Matplotlib has a number of plot types that do this:
frommatplotlib.colorsimportLogNormX,Y=np.meshgrid(np.linspace(-3,3,128),np.linspace(-3,3,128))Z=(1-X/2+X**5+Y**3)*np.exp(-X**2-Y**2)fig,axs=plt.subplots(2,2,layout='constrained')pc=axs[0,0].pcolormesh(X,Y,Z,vmin=-1,vmax=1,cmap='RdBu_r')fig.colorbar(pc,ax=axs[0,0])axs[0,0].set_title('pcolormesh()')co=axs[0,1].contourf(X,Y,Z,levels=np.linspace(-1.25,1.25,11))fig.colorbar(co,ax=axs[0,1])axs[0,1].set_title('contourf()')pc=axs[1,0].imshow(Z**2*100,cmap='plasma',norm=LogNorm(vmin=0.01,vmax=100))fig.colorbar(pc,ax=axs[1,0],extend='both')axs[1,0].set_title('imshow() with LogNorm()')pc=axs[1,1].scatter(data1,data2,c=data3,cmap='RdBu_r')fig.colorbar(pc,ax=axs[1,1],extend='both')axs[1,1].set_title('scatter()')

Colormaps#
These are all examples of Artists that derive fromScalarMappable
objects. They all can set a linear mapping betweenvmin andvmax intothe colormap specified bycmap. Matplotlib has many colormaps to choosefrom (Choosing Colormaps in Matplotlib) you can make yourown (Creating Colormaps in Matplotlib) or download asthird-party packages.
Normalizations#
Sometimes we want a non-linear mapping of the data to the colormap, asin theLogNorm
example above. We do this by supplying theScalarMappable with thenorm argument instead ofvmin andvmax.More normalizations are shown atColormap normalization.
Colorbars#
Adding acolorbar
gives a key to relate the color back to theunderlying data. Colorbars are figure-level Artists, and are attached toa ScalarMappable (where they get their information about the norm andcolormap) and usually steal space from a parent Axes. Placement ofcolorbars can be complex: seePlacing colorbars fordetails. You can also change the appearance of colorbars with theextend keyword to add arrows to the ends, andshrink andaspect tocontrol the size. Finally, the colorbar will have default locatorsand formatters appropriate to the norm. These can be changed as forother Axis objects.
Working with multiple Figures and Axes#
You can open multiple Figures with multiple calls tofig=plt.figure()
orfig2,ax=plt.subplots()
. By keeping theobject references you can add Artists to either Figure.
Multiple Axes can be added a number of ways, but the most basic isplt.subplots()
as used above. One can achieve more complex layouts,with Axes objects spanning columns or rows, usingsubplot_mosaic
.

Matplotlib has quite sophisticated tools for arranging Axes: SeeArranging multiple Axes in a Figure andComplex and semantic figure composition (subplot_mosaic).
More reading#
For more plot types seePlot types and theAPI reference, in particular theAxes API.
Total running time of the script: (0 minutes 9.980 seconds)