Note
Go to the endto download the full example code.
Pyplot tutorial#
An introduction to the pyplot interface. Please also seeQuick start guide for an overview of how Matplotlibworks andMatplotlib Application Interfaces (APIs) for an explanation of the trade-offs between thesupported user APIs.
Introduction to pyplot#
matplotlib.pyplot
is a collection of functions that make matplotlibwork like MATLAB. Eachpyplot
function makes some change to a figure:e.g., creates a figure, creates a plotting area in a figure, plots some linesin a plotting area, decorates the plot with labels, etc.
Inmatplotlib.pyplot
various states are preservedacross function calls, so that it keeps track of things likethe current figure and plotting area, and the plottingfunctions are directed to the current Axes (please note that we use uppercaseAxes to refer to theAxes
concept, which is a centralpart of a figureand not only the plural ofaxis).
Note
The implicit pyplot API is generally less verbose but also not as flexible as theexplicit API. Most of the function calls you see here can also be calledas methods from anAxes
object. We recommend browsing the tutorialsand examples to see how this works. SeeMatplotlib Application Interfaces (APIs) for anexplanation of the trade-off of the supported user APIs.
Generating visualizations with pyplot is very quick:
importmatplotlib.pyplotaspltplt.plot([1,2,3,4])plt.ylabel('some numbers')plt.show()

You may be wondering why the x-axis ranges from 0-3 and the y-axisfrom 1-4. If you provide a single list or array toplot
, matplotlib assumes it is asequence of y values, and automatically generates the x values foryou. Since python ranges start with 0, the default x vector has thesame length as y but starts with 0; therefore, the x data are[0,1,2,3]
.
plot
is a versatile function, and will take an arbitrary number ofarguments. For example, to plot x versus y, you can write:
plt.plot([1,2,3,4],[1,4,9,16])

Formatting the style of your plot#
For every x, y pair of arguments, there is an optional third argumentwhich is the format string that indicates the color and line type ofthe plot. The letters and symbols of the format string are fromMATLAB, and you concatenate a color string with a line style string.The default format string is 'b-', which is a solid blue line. Forexample, to plot the above with red circles, you would issue

See theplot
documentation for a completelist of line styles and format strings. Theaxis
function in the example above takes alist of[xmin,xmax,ymin,ymax]
and specifies the viewport of theAxes.
If matplotlib were limited to working with lists, it would be fairlyuseless for numeric processing. Generally, you will usenumpy arrays. In fact, all sequences areconverted to numpy arrays internally. The example below illustratesplotting several lines with different format styles in one function callusing arrays.

Plotting with keyword strings#
There are some instances where you have data in a format that lets youaccess particular variables with strings. For example, withstructured arraysorpandas.DataFrame
.
Matplotlib allows you to provide such an object withthedata
keyword argument. If provided, then you may generate plots withthe strings corresponding to these variables.
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'])*100plt.scatter('a','b',c='c',s='d',data=data)plt.xlabel('entry a')plt.ylabel('entry b')plt.show()

Plotting with categorical variables#
It is also possible to create a plot using categorical variables.Matplotlib allows you to pass categorical variables directly tomany plotting functions. For example:
names=['group_a','group_b','group_c']values=[1,10,100]plt.figure(figsize=(9,3))plt.subplot(131)plt.bar(names,values)plt.subplot(132)plt.scatter(names,values)plt.subplot(133)plt.plot(names,values)plt.suptitle('Categorical Plotting')plt.show()

Controlling line properties#
Lines have many attributes that you can set: linewidth, dash style,antialiased, etc; seematplotlib.lines.Line2D
. There areseveral ways to set line properties
Use keyword arguments:
Use the setter methods of a
Line2D
instance.plot
returns a listofLine2D
objects; e.g.,line1,line2=plot(x1,y1,x2,y2)
. In the codebelow we will suppose that we have onlyone line so that the list returned is of length 1. We use tuple unpacking withline,
to get the first element of that list:Use
setp
. The example belowuses a MATLAB-style function to set multiple propertieson a list of lines.setp
works transparently with a list of objectsor a single object. You can either use python keyword arguments orMATLAB-style string/value pairs:lines=plt.plot(x1,y1,x2,y2)# use keyword argumentsplt.setp(lines,color='r',linewidth=2.0)# or MATLAB style string value pairsplt.setp(lines,'color','r','linewidth',2.0)
Here are the availableLine2D
properties.
Property | Value Type |
---|---|
alpha | float |
animated | [True | False] |
antialiased or aa | [True | False] |
clip_box | a matplotlib.transform.Bbox instance |
clip_on | [True | False] |
clip_path | a Path instance and a Transform instance, a Patch |
color or c | any matplotlib color |
contains | the hit testing function |
dash_capstyle | [ |
dash_joinstyle | [ |
dashes | sequence of on/off ink in points |
data | (np.array xdata, np.array ydata) |
figure | a matplotlib.figure.Figure instance |
label | any string |
linestyle or ls | [ |
linewidth or lw | float value in points |
marker | [ |
markeredgecolor or mec | any matplotlib color |
markeredgewidth or mew | float value in points |
markerfacecolor or mfc | any matplotlib color |
markersize or ms | float |
markevery | [ None | integer | (startind, stride) ] |
picker | used in interactive line selection |
pickradius | the line pick selection radius |
solid_capstyle | [ |
solid_joinstyle | [ |
transform | a matplotlib.transforms.Transform instance |
visible | [True | False] |
xdata | np.array |
ydata | np.array |
zorder | any number |
To get a list of settable line properties, call thesetp
function with a line or lines as argument
In [69]:lines=plt.plot([1,2,3])In [70]:plt.setp(lines) alpha: float animated: [True | False] antialiased or aa: [True | False] ...snip
Working with multiple figures and Axes#
MATLAB, andpyplot
, have the concept of the current figureand the current Axes. All plotting functions apply to the currentAxes. The functiongca
returns the current Axes (amatplotlib.axes.Axes
instance), andgcf
returns the currentfigure (amatplotlib.figure.Figure
instance). Normally, you don't have toworry about this, because it is all taken care of behind the scenes. Belowis a script to create two subplots.

Thefigure
call here is optional because a figure will be createdif none exists, just as an Axes will be created (equivalent to an explicitsubplot()
call) if none exists.Thesubplot
call specifiesnumrows,numcols,plot_number
whereplot_number
ranges from 1 tonumrows*numcols
. The commas in thesubplot
call areoptional ifnumrows*numcols<10
. Sosubplot(211)
is identicaltosubplot(2,1,1)
.
You can create an arbitrary number of subplotsand Axes. If you want to place an Axes manually, i.e., not on arectangular grid, useaxes
,which allows you to specify the location asaxes([left,bottom,width,height])
where all values are in fractional (0 to 1)coordinates. SeeAxes Demo for an example ofplacing Axes manually andMultiple subplots for anexample with lots of subplots.
You can create multiple figures by using multiplefigure
calls with an increasing figurenumber. Of course, each figure can contain as many Axes and subplotsas your heart desires:
importmatplotlib.pyplotaspltplt.figure(1)# the first figureplt.subplot(211)# the first subplot in the first figureplt.plot([1,2,3])plt.subplot(212)# the second subplot in the first figureplt.plot([4,5,6])plt.figure(2)# a second figureplt.plot([4,5,6])# creates a subplot() by defaultplt.figure(1)# first figure current;# subplot(212) still currentplt.subplot(211)# make subplot(211) in the first figure# currentplt.title('Easy as 1, 2, 3')# subplot 211 title
You can clear the current figure withclf
and the current Axes withcla
. If you findit annoying that states (specifically the current image, figure and Axes)are being maintained for you behind the scenes, don't despair: this is just a thinstateful wrapper around an object-oriented API, which you can useinstead (seeArtist tutorial)
If you are making lots of figures, you need to be aware of onemore thing: the memory required for a figure is not completelyreleased until the figure is explicitly closed withclose
. Deleting all references to thefigure, and/or using the window manager to kill the window in whichthe figure appears on the screen, is not enough, because pyplotmaintains internal references untilclose
is called.
Working with text#
text
can be used to add text in an arbitrary location, andxlabel
,ylabel
andtitle
are used to addtext in the indicated locations (seeText in Matplotlib for amore detailed example)
mu,sigma=100,15x=mu+sigma*np.random.randn(10000)# the histogram of the datan,bins,patches=plt.hist(x,50,density=True,facecolor='g',alpha=0.75)plt.xlabel('Smarts')plt.ylabel('Probability')plt.title('Histogram of IQ')plt.text(60,.025,r'$\mu=100,\ \sigma=15$')plt.axis([40,160,0,0.03])plt.grid(True)plt.show()

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 or usingsetp
:
t=plt.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:
plt.title(r'$\sigma_i=15$')
Ther
preceding the title string is important -- it signifiesthat the string is araw string and not to treat backslashes aspython escapes. matplotlib has a built-in TeX expression parser andlayout engine, and ships its own math fonts -- for details seeWriting mathematical expressions. Thus, you can use mathematical text acrossplatforms without requiring a TeX installation. For those who have LaTeXand dvipng installed, you can also use LaTeX to format your text andincorporate the output directly into your display figures or savedpostscript -- seeText rendering with LaTeX.
Annotating text#
The uses of the basictext
function aboveplace text at an arbitrary position on the Axes. A common use fortext is to annotate some feature of the plot, and theannotate
method provides helperfunctionality to make annotations easy. In an annotation, there aretwo points to consider: the location being annotated represented bythe argumentxy
and the location of the textxytext
. Both ofthese arguments are(x,y)
tuples.

In this basic example, both thexy
(arrow tip) andxytext
locations (text location) are in data coordinates. There are avariety of other coordinate systems one can choose -- seeBasic annotation andAdvanced annotation fordetails. More examples can be found inAnnotate plots.
Logarithmic and other nonlinear axes#
matplotlib.pyplot
supports not only linear axis scales, but alsologarithmic and logit scales. This is commonly used if data spans many ordersof magnitude. Changing the scale of an axis is easy:
plt.xscale('log')
An example of four plots with the same data and different scales for the y-axisis shown below.
# Fixing random state for reproducibilitynp.random.seed(19680801)# make up some data in the open interval (0, 1)y=np.random.normal(loc=0.5,scale=0.4,size=1000)y=y[(y>0)&(y<1)]y.sort()x=np.arange(len(y))# plot with various axes scalesplt.figure()# linearplt.subplot(221)plt.plot(x,y)plt.yscale('linear')plt.title('linear')plt.grid(True)# logplt.subplot(222)plt.plot(x,y)plt.yscale('log')plt.title('log')plt.grid(True)# symmetric logplt.subplot(223)plt.plot(x,y-y.mean())plt.yscale('symlog',linthresh=0.01)plt.title('symlog')plt.grid(True)# logitplt.subplot(224)plt.plot(x,y)plt.yscale('logit')plt.title('logit')plt.grid(True)# Adjust the subplot layout, because the logit one may take more space# than usual, due to y-tick labels like "1 - 10^{-3}"plt.subplots_adjust(top=0.92,bottom=0.08,left=0.10,right=0.95,hspace=0.25,wspace=0.35)plt.show()

It is also possible to add your own scale, seematplotlib.scale
fordetails.
Total running time of the script: (0 minutes 3.950 seconds)