Professional Documents
Culture Documents
Pyplot Tutorial - Matplotlib 3.3.3 Documentation
Pyplot Tutorial - Matplotlib 3.3.3 Documentation
Pyplot Tutorial - Matplotlib 3.3.3 Documentation
3
Fork me on GitHub
home | cont ent s » User's Guide » Tutorials » Pyplot t utorial previous | next | modules | index
Table of Contents
Pyplot tutorial Pyplot t utorial
An int roduct ion to t he pyplot int erface.
Int ro to pyplot
Format t ing t he st yle of
Intro to pyplot your plot
matplotlib.pyplot is a collect ion of funct ions t hat make mat plot lib Plot t ing wit h keyword st rings
work like MAT LAB. Each pyplot funct ion makes some change to a Plot t ing wit h cat egorical
variables
figure: e.g., creat es a figure, creat es a plot t ing area in a figure, plot s
Cont rolling line propert ies
some lines in a plot t ing area, decorat es t he plot wit h labels, et c. Working wit h mult iple figures
and axes
In matplotlib.pyplot various st at es are preserved across funct ion
Working wit h t ext
calls, so t hat it keeps t rack of t hings like t he current figure and plot t ing
Using mat hemat ical
area, and t he plot t ing funct ions are direct ed to t he current axes
expressions in t ext
(please not e t hat "axes" here and in most places in t he document at ion
Annot at ing t ext
refers to t he axes part of a figure and not t he st rict mat hemat ical t erm
Logarit hmic and ot her
for more t han one axis).
nonlinear axes
t he pyplot API is generally less-flexible t han t he object -orient ed Document at ion overview
API. Most of t he funct ion calls you see here can also be called as User's Guide
met hods from an Axes object . We recommend browsing t he Tutorials
t utorials and examples to see how t his works.
Previous: Usage Guide
Next : Sample plot s in
Generat ing visualizat ions wit h pyplot is very quick: Mat plot lib
plot is a versat ile funct ion, and will t ake an arbit rary number of
argument s. For example, to plot x versus y, you can writ e:
See t he plot document at ion for a complet e list of line st yles and
format st rings. T he axis funct ion in t he example above t akes a list of
[xmin, xmax, ymin, ymax] and specifies t he viewport of t he axes.
If mat plot lib were limit ed to working wit h list s, it would be fairly useless
for numeric processing. Generally, you will use numpy arrays. In fact , all
sequences are convert ed to numpy arrays int ernally. T he example
below illust rat es plot t ing several lines wit h different format st yles in
one funct ion call using arrays.
import numpy as np
Mat plot lib allows you provide such an object wit h t he data keyword
argument . If provided, t hen you may generat e plot s wit h t he st rings
corresponding to t hese variables.
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()
plt.plot(x, y, linewidth=2.0)
Use t he set t er met hods of a Line2D inst ance. plot ret urns a
list of Line2D object s; e.g., line1, line2 = plot(x1, y1,
x2, y2). In t he code below we will suppose t hat we have only
one line so t hat t he list ret urned is of lengt h 1. We use t uple
unpacking wit h line, to get t he first element of t hat list :
Use setp. T he example below uses a MAT LAB-st yle funct ion to
set mult iple propert ies on a list of lines. setp works
t ransparent ly wit h a list of object s or a single object . You can
eit her use pyt hon keyword argument s or MAT LAB-st yle
st ring/value pairs:
To get a list of set t able line propert ies, call t he setp funct ion wit h a
line or lines as argument
In [70]: plt.setp(lines)
alpha: float
animated: [True | False]
antialiased or aa: [True | False]
...snip
def f(t):
return np.exp(-t) * np.cos(2*np.pi*t)
plt.figure()
plt.subplot(211)
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')
plt.subplot(212)
plt.plot(t2, np.cos(2*np.pi*t2), 'r--')
plt.show()
You can creat e an arbit rary number of subplot s and axes. If you want to
place an axes manually, i.e., not on a rect angular grid, use axes, which
allows you to specify t he locat ion as axes([left, bottom, width,
height]) where all values are in fract ional (0 to 1) coordinat es. See
Axes Demo for an example of placing axes manually and Basic Subplot
Demo for an example wit h lot s of subplot s.
You can creat e mult iple figures by using mult iple figure calls wit h an
increasing figure number. Of course, each figure can cont ain as many
axes and subplot s as your heart desires:
You can clear t he current figure wit h clf and t he current axes wit h cla.
If you find it annoying t hat st at es (specifically t he current image, figure
and axes) are being maint ained for you behind t he scenes, don't
despair: t his is just a t hin st at eful wrapper around an object orient ed
API, which you can use inst ead (see Art ist t utorial)
If you are making lot s of figures, you need to be aware of one more
t hing: t he memory required for a figure is not complet ely released unt il
t he figure is explicit ly closed wit h close. Delet ing all references to t he
figure, and/or using t he window manager to kill t he window in which t he
figure appears on t he screen, is not enough, because pyplot maint ains
int ernal references unt il close is called.
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 t he text funct ions ret urn a matplotlib.text.Text inst ance.
Just as wit h wit h lines above, you can customize t he propert ies by
passing keyword argument s into t he t ext funct ions or using setp:
T hese propert ies are covered in more det ail in Text propert ies and
layout .
plt.title(r'$\sigma_i=15$')
Annota ng text
T he uses of t he basic text funct ion above place t ext at an arbit rary
posit ion on t he Axes. A common use for t ext is to annot at e some
feat ure of t he plot , and t he annotate met hod provides helper
funct ionalit y to make annot at ions easy. In an annot at ion, t here are t wo
point s to consider: t he locat ion being annot at ed represent ed by t he
argument xy and t he locat ion of t he t ext xytext. Bot h of t hese
argument s are (x, y) t uples.
ax = plt.subplot(111)
plt.ylim(-2, 2)
plt.show()
In t his basic example, bot h t he xy (arrow t ip) and xytext locat ions
(t ext locat ion) are in dat a coordinat es. T here are a variet y of ot her
coordinat e syst ems one can choose -- see Basic annot at ion and
Advanced Annot at ions for det ails. More examples can be found in
Annot at ing Plot s.
plt .xscale('log')
An example of four plot s wit h t he same dat a and different scales for
t he y axis is shown below.
# linear
plt.subplot(221)
plt.plot(x, y)
plt.yscale('linear')
plt.title('linear')
plt.grid(True)
# log
plt.subplot(222)
plt.plot(x, y)
plt.yscale('log')
plt.title('log')
plt.grid(True)
# symmetric log
plt.subplot(223)
plt.plot(x, y - y.mean())
plt.yscale('symlog', linthresh=0.01)
plt.title('symlog')
plt.grid(True)
# logit
plt.subplot(224)
plt.plot(x, y)
plt.yscale('logit')
plt.title('logit')
plt.grid(True)
# Adjust the subplot layout, because the logit one may tak
# than usual, due to y-tick labels like "1 - 10^{-3}"
plt.subplots_adjust(top=0.92, bottom=0.08, left=0.10, r
wspace=0.35)
plt.show()
It is also possible to add your own scale, see Developer's guide for
creat ing scales and t ransformat ions for det ails.
© Copyright 2002 - 2012 John Hunter, Darren Dale, Eric Firing, Michael Droettboom and the Matplotlib developm ent team ; 2012 - 2020 The
Matplotlib developm ent team .
Last updated on Nov 12, 2020. Created using Sphinx 3.1.1. Doc version v3.3.3-2-g447bdbbf58.