Pyplot Tutorial - Matplotlib 3.3.3 Documentation

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

Version 3.3.

3
Fork me on GitHub

Installa on Documenta on Examples Tutorials Contribu ng Search

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

Note Related Topics

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

Show Page Source


import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4])
plt.ylabel('some numbers')
plt.show()
You may be wondering why t he x-axis ranges from 0-3 and t he y-axis
from 1-4. If you provide a single list or array to plot, mat plot lib
assumes it is a sequence of y values, and automat ically generat es t he
x values for you. Since pyt hon ranges st art wit h 0, t he default x vector
has t he same lengt h as y but st art s wit h 0. Hence t he x dat a are [0,
1, 2, 3].

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:

plt.plot([1, 2, 3, 4], [1, 4, 9, 16])

Out : [<matplotlib.lines.Line2D object at 0x7fba1f31f790>


Forma ng the style of your plot
For every x, y pair of argument s, t here is an opt ional t hird argument
which is t he format st ring t hat indicat es t he color and line t ype of t he
plot . T he let t ers and symbols of t he format st ring are from MAT LAB,
and you concat enat e a color st ring wit h a line st yle st ring. T he default
format st ring is 'b-', which is a solid blue line. For example, to plot t he
above wit h red circles, you would issue

plt.plot([1, 2, 3, 4], [1, 4, 9, 16], 'ro')


plt.axis([0, 6, 0, 20])
plt.show()

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

# evenly sampled time at 200ms intervals


t = np.arange(0., 5., 0.2)

# red dashes, blue squares and green triangles


plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
plt.show()
Plo ng with keyword strings
T here are some inst ances where you have dat a in a format t hat let s
you access part icular variables wit h st rings. For example, wit h
numpy.recarray or pandas.DataFrame.

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.

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']) * 100

plt.scatter('a', 'b', c='c', s='d', data=data)


plt.xlabel('entry a')
plt.ylabel('entry b')
plt.show()
Plo ng with categorical variables
It is also possible to creat e a plot using cat egorical variables. Mat plot lib
allows you to pass cat egorical variables direct ly to many plot t ing
funct ions. 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 proper es


Lines have many at t ribut es t hat you can set : linewidt h, dash st yle,
ant ialiased, et c; see matplotlib.lines.Line2D. T here are several
ways to set line propert ies

Use keyword args:

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 :

line, = plt.plot(x, y, '-')


line.set_antialiased(False) # turn off antialiasing

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:

lines = plt.plot(x1, y1, x2, y2)


# use keyword args
plt.setp(lines, color='r', linewidth=2.0)
# or MATLAB style string value pairs
plt.setp(lines, 'color', 'r', 'linewidth', 2.0)

Here are t he available Line2D propert ies.

Property Value Type


alpha float
animat ed [True | False]
ant ialiased or aa [True | False]
clip_ box a mat plot lib.t ransform.Bbox inst ance
clip_ on [True | False]
clip_ pat h a Pat h inst ance and a Transform inst ance, a Pat ch
color or c any mat plot lib color
cont ains t he hit t est ing funct ion
dash_ capst yle ['butt' | 'round' | 'projecting']
dash_ joinst yle ['miter' | 'round' | 'bevel']
dashes sequence of on/off ink in point s
dat a (np.array xdat a, np.array ydat a)
Property Value Type
figure a mat plot lib.figure.Figure inst ance
label any st ring
linest yle or ls [ '-' | '--' | '-.' | ':' | 'steps' | ...]
linewidt h or lw float value in point s
marker [ '+' | ',' | '.' | '1' | '2' | '3' | '4' ]
markeredgecolor any mat plot lib color
or mec
markeredgewidt h float value in point s
or mew
markerfacecolor any mat plot lib color
or mfc
markersize or ms float
markevery [ None | int eger | (st art ind, st ride) ]
picker used in int eract ive line select ion
pickradius t he line pick select ion radius
solid_ capst yle ['butt' | 'round' | 'projecting']
solid_ joinst yle ['miter' | 'round' | 'bevel']
t ransform a mat plot lib.t ransforms.Transform inst ance
visible [True | False]
xdat a np.array
ydat a np.array
zorder any number

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 [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 mul ple figures and axes


MAT LAB, and pyplot, have t he concept of t he current figure and t he
current axes. All plot t ing funct ions apply to t he current axes. T he
funct ion gca ret urns t he current axes (a matplotlib.axes.Axes
inst ance), and gcf ret urns t he current figure (a
matplotlib.figure.Figure inst ance). Normally, you don't have to
worry about t his, because it is all t aken care of behind t he scenes.
Below is a script to creat e t wo subplot s.

def f(t):
return np.exp(-t) * np.cos(2*np.pi*t)

t1 = np.arange(0.0, 5.0, 0.1)


t2 = np.arange(0.0, 5.0, 0.02)

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()

T he figure call here is opt ional because figure(1) will be creat ed by


default , just as a subplot(111) will be creat ed by default if you don't
manually specify any axes. T he subplot call specifies numrows,
numcols, plot_number where plot_number ranges from 1 to
numrows*numcols. T he commas in t he subplot call are opt ional if
numrows*numcols<10. So subplot(211) is ident ical to subplot(2,
1, 1).

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:

import matplotlib.pyplot as plt


plt.figure(1) # the first figure
plt.subplot(211) # the first subplot in the
plt.plot([1, 2, 3])
plt.subplot(212) # the second subplot in the
plt.plot([4, 5, 6])

plt.figure(2) # a second figure


plt.plot([4, 5, 6]) # creates a subplot(111) by

plt.figure(1) # figure 1 current; subplot


plt.subplot(211) # make subplot(211) in figu
plt.title('Easy as 1, 2, 3') # subplot 211 title

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.

Working with text


text can be used to add t ext in an arbit rary locat ion, and xlabel,
ylabel and title are used to add t ext in t he indicat ed locat ions (see
Text in Mat plot lib Plot s for a more det ailed example)

mu, sigma = 100, 15


x = mu + sigma * np.random.randn(10000)

# the histogram of the data


n, bins, patches = plt.hist(x, 50, density=1, facecolor

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 = plt.xlabel('my data', fontsize=14, color='red')

T hese propert ies are covered in more det ail in Text propert ies and
layout .

Using mathema cal expressions in text


mat plot lib accept s TeX equat ion expressions in any t ext expression.
For example to writ e t he expression σi = 15 in t he t it le, you can writ e a
TeX expression surrounded by dollar signs:

plt.title(r'$\sigma_i=15$')

T he r preceding t he t it le st ring is import ant -- it signifies t hat t he


st ring is a raw st ring and not to t reat backslashes as pyt hon escapes.
mat plot lib has a built -in TeX expression parser and layout engine, and
ships it s own mat h font s -- for det ails see Writ ing mat hemat ical
expressions. T hus you can use mat hemat ical t ext across plat forms
wit hout requiring a TeX inst allat ion. For t hose who have LaTeX and
dvipng inst alled, you can also use LaTeX to format your t ext and
incorporat e t he out put direct ly into your display figures or saved
post script -- see Text rendering Wit h LaTeX.

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)

t = np.arange(0.0, 5.0, 0.01)


s = np.cos(2*np.pi*t)
line, = plt.plot(t, s, lw=2)

plt.annotate('local max', xy=(2, 1), xytext=(3, 1.5),


arrowprops=dict(facecolor='black', shrink=
)

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.

Logarithmic and other nonlinear axes


matplotlib.pyplot support s not only linear axis scales, but also
logarit hmic and logit scales. T his is commonly used if dat a spans many
orders of magnit ude. Changing t he scale of an axis is easy:

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.

# Fixing random state for reproducibility


np.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 scales


plt.figure()

# 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.

Total running time of the script: ( 0 minut es 4.110 seconds)

Download Python source code: pyplot.py

Download Jupyter notebook: pyplot.ipynb

© 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.

You might also like