Matplotlib Tutorial: Nicolas Rougier
Matplotlib Tutorial: Nicolas Rougier
Nicolas Rougier
Introduction
Simple plot
Figures, Subplots, Axes and Ticks
Other Types of Plots
Beyond this tutorial
Quick references
Note This tutorial is based on Mike Müller's tutorial available from the scipy
There is now an accompanying lecture notes.
numpy tutorial.
Sources are available here. Figures are in the figures directory and all
scripts are located in the scripts directory. Github repository is here
Many thanks to Bill Wing and Christoph Deil for review and
corrections.
Introduction
matplotlib is probably the single most used Python package for 2D-
graphics. It provides both a very quick way to visualize data from
Python and publication-quality figures in many formats. We are going
to explore matplotlib in interactive mode covering most common
cases.
IPython and the pylab mode
pylab
Simple plot
In this section, we want to draw the cosine and sine functions on the
same plot. Starting from the default settings, we'll enrich the figure step
by step to make it nicer.
First step is to get the data for the sine and cosine functions:
$ ipython --pylab
This brings us to the IPython prompt:
or you can download each of the examples and run it using regular
python:
$ python exercice_1.py
You can get source for each step by clicking on the corresponding
figure.
Using defaults
Documentation
plot tutorial
plot() command
plot(X,C)
plot(X,S)
show()
Instantiating defaults
Documentation
Customizing matplotlib
In the script below, we've instantiated (and commented) all the figure
settings that influence the appearance of the plot. The settings have
been explicitly set to their default values, but now you can
interactively play with the values to explore their affect (see Line
properties and Line styles below).
# Create a new figure of size 8x6 points, using 80 dots per inc
h
figure(figsize=(8,6), dpi=80)
# Set x limits
xlim(-4.0,4.0)
# Set x ticks
xticks(np.linspace(-4,4,9,endpoint=True))
# Set y limits
ylim(-1.0,1.0)
# Set y ticks
yticks(np.linspace(-1,1,5,endpoint=True))
Documentation
Controlling line properties
Line API
First step, we want to have the cosine in blue and the sine in red and a
slighty thicker line for both of them. We'll also slightly alter the figure
size to make it more horizontal.
...
figure(figsize=(10,6), dpi=80)
plot(X, C, color="blue", linewidth=2.5, linestyle="-")
plot(X, S, color="red", linewidth=2.5, linestyle="-")
...
Setting limits
Documentation Current limits of the figure are a bit too tight and we want to make
xlim() command some space in order to clearly see all data points.
ylim() command
...
xlim(X.min()*1.1, X.max()*1.1)
ylim(C.min()*1.1, C.max()*1.1)
...
Setting ticks
Documentation
xticks() command
yticks() command
Tick container
Tick locating and formatting
Current ticks are not ideal because they do not show the interesting
values (+/-π,+/-π/2) for sine and cosine. We'll change them such that
they show only these values.
...
xticks( [-np.pi, -np.pi/2, 0, np.pi/2, np.pi])
yticks([-1, 0, +1])
...
Documentation Ticks are now properly placed but their label is not very explicit. We
Working with text could guess that 3.142 is π but it would be better to make it explicit.
xticks() command
yticks() command
set_xticklabels()
set_yticklabels()
...
xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],
[r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$']
)
yticks([-1, 0, +1],
[r'$-1$', r'$0$', r'$+1$'])
...
Moving spines
Documentation
Spines
Axis container
Transformations tutorial
Spines are the lines connecting the axis tick marks and noting the
boundaries of the data area. They can be placed at arbitrary positions
and until now, they were on the border of the axis. We'll change that
since we want to have them in the middle. Since there are four of them
(top/bottom/left/right), we'll discard the top and right by setting their
color to none and we'll move the bottom and left ones to coordinate 0
in data space coordinates.
...
ax = gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))
...
Adding a legend
Documentation
Legend guide
legend() command
Legend API
Let's add a legend in the upper left corner. This only requires adding
the keyword argument label (that will be used in the legend box) to the
plot commands.
...
plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="c
osine")
plot(X, S, color="red", linewidth=2.5, linestyle="-", label="s
ine")
legend(loc='upper left')
...
Documentation Let's annotate some interesting points using the annotate command.
Annotating axis
annotate() command
We chose the 2π/3 value and we want to annotate both the sine and
the cosine. We'll first draw a marker on the curve as well as a straight
dotted line. Then, we'll use the annotate command to display some
text with an arrow.
...
t = 2*np.pi/3
plot([t,t],[0,np.cos(t)], color ='blue', linewidth=2.5, linesty
le="--")
scatter([t,],[np.cos(t),], 50, color ='blue')
annotate(r'$\sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$',
xy=(t, np.sin(t)), xycoords='data',
xytext=(+10, +30), textcoords='offset points', fontsiz
e=16,
arrowprops=dict(arrowstyle="->", connectionstyle="arc3
,rad=.2"))
annotate(r'$\cos(\frac{2\pi}{3})=-\frac{1}{2}$',
xy=(t, np.cos(t)), xycoords='data',
xytext=(-90, -50), textcoords='offset points', fontsiz
e=16,
arrowprops=dict(arrowstyle="->", connectionstyle="arc3
,rad=.2"))
...
Documentation The tick labels are now hardly visible because of the blue and red
Artists lines. We can make them bigger and we can also adjust their
BBox
properties such that they'll be rendered on a semi-transparent white
background. This will allow us to see both the data and the labels.
...
f
o
r
l
a
b
e
l
i
n
a
x
.
g
e
t
_
x
t
icklabels() + ax.get_yticklabels():
label.set_fontsize(16)
label.set_bbox(dict(facecolor='white', edgecolor='None', al
pha=0.65 ))
...
Figures
A figure is the windows in the GUI that has "Figure #" as title. Figures
are numbered starting from 1 as opposed to the normal Python way
starting from 0. This is clearly MATLAB-style. There are several
parameters that determine what the figure looks like:
Argument Default Description
num 1 number of figure
figsize figure.figsize figure size in in inches (width, height)
dpi figure.dpi resolution in dots per inch
facecolor figure.facecolor color of the drawing background
edgecolor figure.edgecolor color of edge around the drawing
background
frameon True draw figure frame or not
The defaults can be specified in the resource file and will be used most
of the time. Only the number of the figure is frequently changed.
When you work with the GUI you can close a figure by clicking on the
x in the upper right corner. But you can close a figure
programmatically by calling close. Depending on the argument it
closes (1) the current figure (no argument), (2) a specific figure (figure
number or figure instance as argument), or (3) all figures (all as
argument).
As with other objects, you can set figure properties also setp or with
the set_something methods.
Subplots
With subplot you can arrange plots in a regular grid. You need to
specify the number of rows and columns and the number of the plot.
Note that the gridspec command is a more powerful alternative.
Axes
Axes are very similar to subplots but allow placement of plots at any
location in the figure. So if we want to put a smaller plot inside a
bigger one we do so with axes.
Ticks
Tick Locators
Class Description
NullLocator No ticks.
n = 256
X = np.linspace(-n
p.pi,np.pi,n,endpo
int=True)
Y = np.sin(2*X)
Scatter Plots
n = 1024
X = np.random.norm
al(0,1,n)
Y = np.random.normal(0,1,n)
scatter(X,Y)
show()
n = 12
X = np.arange(n)
Y1 = (1-X/float(n)
) * np.random.unif
orm(0.5,1.0,n)
Y2 = (1-X/float(n)) * np.random.uniform(0.5,1.0,n)
ylim(-1.25,+1.25)
show()
Contour Plots
n = 256
x = np.linspace(-3,3,n)
y = np.linspace(-3,3,n)
X,Y = np.meshgrid(x,y)
Imshow
n = 10
x = np.linspace(-3,3,4*n)
y = np.linspace(-3,3,3*n)
X,Y = np.meshgrid(x,y)
imshow(f(X,Y)), show()
Pie Charts
n = 20
Z = np.random.unif
orm(0,1,n)
pie(Z), show()
n = 8
X,Y = np.mgrid[0:n
,0:n]
quiver(X,Y), show(
)
Grids
axes = gca()
axes.set_xlim(0,4)
axes.set_ylim(0,3)
axes.set_xticklabe
ls([])
axes.set_yticklabels([])
show()
Multi Plots
Hints Starting from the
You can use several subplots code below, try to
with different partition.
reproduce the
graphic on the right.
subplot(2,2,1)
subplot(2,2,3)
subplot(2,2,4)
show()
Polar Axis
axes([0,0,1,1])
N = 20
theta = np.arange(
0.0, 2*np.pi, 2*np
.pi/N)
radii = 10*np.rand
om.rand(N)
width = np.pi/4*np.random.rand(N)
bars = bar(theta, radii, width=width, bottom=0.0)
show()
3D Plots
Starting from the code below, try to reproduce the graphic on the right.
fig = figure()
ax = Axes3D(fig)
X = np.arange(-4,
4, 0.25)
Y = np.arange(-4,
4, 0.25)
X, Y = np.meshgrid
(X, Y)
R = np.sqrt(X**2 +
Y**2)
Z = np.sin(R)
ax.plot_surface(X,
Y, Z, rstride=1, cstride=1, cmap='hot')
show()
Text
Tutorials
Pyplot tutorial
Introduction
Controlling line properties
Working with multiple figures and axes
Working with text
Image tutorial
Startup commands
Importing image data into Numpy arrays
Plotting numpy arrays as images
Text tutorial
Text introduction
Basic text commands
Text properties and layout
Writing mathematical expressions
Text rendering With LaTeX
Annotating text
Artist tutorial
Introduction
Customizing your objects
Object containers
Figure container
Axes container
Axis containers
Tick containers
Path tutorial
Introduction
Bézier example
Compound paths
Transforms tutorial
Introduction
Data coordinates
Axes coordinates
Blended transformations
Using offset transforms to create a shadow effect
The transformation pipeline
Matplotlib documentation
User guide
FAQ
Installation
Usage
How-To
Troubleshooting
Environment Variables
Screenshots
Code documentation
The code is fairly well documented and you can quickly access a
specific command from within a python session:
plot(*args, **kwargs)
Plot lines and/or markers to the
:class:`~matplotlib.axes.Axes`. *args* is a variable length
argument, allowing for multiple *x*, *y* pairs with an
optional format string. For example, each of the following
is
legal::
Galleries
The matplotlib gallery is also incredibly useful when you search how
to render a given graphic. Each example comes with its source.
Mailing lists
Finally, there is a user mailing list where you can ask for help and a
developers mailing list that is more technical.
Quick references
Here is a set of tables that show main properties and styles.
Line properties
s square
+ plus
x cross
D diamond
d thin diamond
1 tripod down
2 tripod up
3 tripod left
4 tripod right
h hexagon
H rotated hexagon
p pentagon
| vertical line
_ horizontal line
Markers
7 caret down
o circle
D diamond
h hexagon 1
H hexagon 2
_ horizontal line
1 tripod down
2 tripod up
3 tripod left
4 tripod right
8 octagon
p pentagon
^ triangle up
v triangle down
< triangle left
> triangle right
d thin diamond
, pixel
+ plus
. point
s square
* star
| vertical line
x cross
r'$\sqrt{2}$' any latex expression
Colormaps
Base
Name Appearance
autumn
bone
cool
copper
flag
gray
hot
hsv
jet
pink
prism
spectral
spring
summer
winter
GIST
Name Appearance
gist_earth
gist_gray
gist_heat
gist_ncar
gist_rainbow
gist_stern
gist_yarg
Sequential
Name Appearance
BrBG
PiYG
PRGn
PuOr
RdBu
RdGy
RdYlBu
RdYlGn
Spectral
Diverging
Name Appearance
Blues
BuGn
BuPu
GnBu
Greens
Greys
Oranges
OrRd
PuBu
PuBuGn
PuRd
Purples
RdPu
Reds
YlGn
YlGnBu
YlOrBr
YlOrRd
Qualitative
Name Appearance
Accent
Dark2
Paired
Pastel1
Pastel2
Set1
Set2
Set3
Miscellaneous
Name Appearance
afmhot
binary
brg
bwr
coolwarm
CMRmap
cubehelix
gnuplot
gnuplot2
ocean
rainbow
seismic
terrain