matplotlib - a tutorial
TRANSCRIPT
Note
There is now an accompanying
numpy tutorial.
Matplotlib tutorialNicolas P. Rougier - Euroscipy 2012 - Prace 2013 -
Euroscipy 2013
Introduction
Simple plot
Figures, Subplots, Axes and Ticks
Other Types of Plots
Beyond this tutorial
Quick references
This tutorial is based on Mike Müller's tutorial available from the scipy
lecture notes.
Sources are available here. Figures are in the figures directory and all
scripts are located in the scripts directory. Github repository is here
All code and material is licensed under a Creative Commons
Attribution 3.0 United States License (CC-by)
http://creativecommons.org/licenses/by/3.0/us
Many thanks to Bill Wing and Christoph Deil for review and
corrections.
Introductory slides on scientific visualization are here
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
IPython is an enhanced interactive Python shell that has lots of
interesting features including named inputs and outputs, access to shell
commands, improved debugging and many more. When we start it
with the command line argument -pylab (--pylab since IPython version
0.12), it allows interactive matplotlib sessions that have
Matlab/Mathematica-like functionality.
pylab
pylab provides a procedural interface to the matplotlib object-oriented
plotting library. It is modeled closely after Matlab(TM). Therefore, the
majority of plotting commands in pylab have Matlab(TM) analogs with
similar arguments. Important commands are explained with interactive
examples.
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:
from pylab import *
X = np.linspace(-np.pi, np.pi, 256,endpoint=True)C,S = np.cos(X), np.sin(X)
X is now a numpy array with 256 values ranging from -π to +π
(included). C is the cosine (256 values) and S is the sine (256 values).
To run the example, you can type them in an IPython interactive
session
$ ipython --pylab
This brings us to the IPython prompt:
IPython 0.13 -- An enhanced Interactive Python.? -> Introduction to IPython's features.%magic -> Information about IPython's 'magic' % functions.
Documentation
plot tutorial
plot() command
help -> Python's own help system.object? -> Details about 'object'. ?object also works, ?? prints more.
Welcome to pylab, a matplotlib-based Python environment.For more information, type 'help(pylab)'.
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
Matplotlib comes with a set of default settings that allow customizing
all kinds of properties. You can control the defaults of almost every
property in matplotlib: figure size and dpi, line width, color and style,
axes, axis and grid properties, text and font properties and so on.
While matplotlib defaults are rather good in most cases, you may want
to modify some properties for specific cases.
from pylab import *
X = np.linspace(-np.pi, np.pi, 256,endpoint=True)C,S = np.cos(X), np.sin(X)
plot(X,C)plot(X,S)
show()
Documentation
Customizing matplotlib
Instantiating defaults
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).
# Import everything from matplotlib (numpy is accessible via 'np' alias)from pylab import *
# Create a new figure of size 8x6 points, using 80 dots per inchfigure(figsize=(8,6), dpi=80)
# Create a new subplot from a grid of 1x1subplot(1,1,1)
X = np.linspace(-np.pi, np.pi, 256,endpoint=True)C,S = np.cos(X), np.sin(X)
# Plot cosine using blue color with a continuous line of width 1 (pixels)plot(X, C, color="blue", linewidth=1.0, linestyle="-")
# Plot sine using green color with a continuous line of width 1 (pixels)plot(X, S, color="green", linewidth=1.0, linestyle="-")
# Set x limitsxlim(-4.0,4.0)
# Set x ticksxticks(np.linspace(-4,4,9,endpoint=True))
# Set y limitsylim(-1.0,1.0)
# Set y ticks
Documentation
Controlling line properties
Line API
Documentation
xlim() command
ylim() command
yticks(np.linspace(-1,1,5,endpoint=True))
# Save figure using 72 dots per inch# savefig("exercice_2.png",dpi=72)
# Show result on screenshow()
Changing colors and line widths
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
Current limits of the figure are a bit too tight and we want to make
some space in order to clearly see all data points.
...xlim(X.min()*1.1, X.max()*1.1)ylim(C.min()*1.1, C.max()*1.1)...
Documentation
xticks() command
yticks() command
Tick container
Tick locating and formatting
Documentation
Working with text
xticks() command
Setting ticks
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])...
Setting tick labels
Ticks are now properly placed but their label is not very explicit. We
could guess that 3.142 is π but it would be better to make it explicit.
yticks() command
set_xticklabels()
set_yticklabels()
Documentation
Spines
Axis container
Transformations tutorial
When we set tick values, we can also provide a corresponding label in
the second argument list. Note that we'll use latex to allow for nice
rendering of the label.
...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
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
Documentation
Legend guide
legend() command
Legend API
Documentation
(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
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="cosine")plot(X, S, color="red", linewidth=2.5, linestyle="-", label="sine")
legend(loc='upper left')...
Annotate some points
Let's annotate some interesting points using the annotate command.
Annotating axis
annotate() command
Documentation
Artists
BBox
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/3plot([t,t],[0,np.cos(t)], color ='blue', linewidth=2.5, linestyle="--")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', fontsize=16, arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))
plot([t,t],[0,np.sin(t)], color ='red', linewidth=2.5, linestyle="--")scatter([t,],[np.sin(t),], 50, color ='red')
annotate(r'$\cos(\frac{2\pi}{3})=-\frac{1}{2}$', xy=(t, np.cos(t)), xycoords='data', xytext=(-90, -50), textcoords='offset points', fontsize=16, arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))...
Devil is in the details
The tick labels are now hardly visible because of the blue and red
lines. We can make them bigger and we can also adjust their
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.
...
for label in ax.get_xticklabels() + ax.get_yticklabels(): label.set_fontsize(16) label.set_bbox(dict(facecolor='white', edgecolor='None', alpha=0.65 ))...
Figures, Subplots, Axes and Ticks
So far we have used implicit figure and axes creation. This is handy for
fast plots. We can have more control over the display using figure,
subplot, and axes explicitly. A figure in matplotlib means the whole
window in the user interface. Within this figure there can be subplots.
While subplot positions the plots in a regular grid, axes allows free
placement within the figure. Both can be useful depending on your
intention. We've already worked with figures and subplots without
explicitly calling them. When we call plot, matplotlib calls gca() to get
the current axes and gca in turn calls gcf() to get the current figure. If
there is none it calls figure() to make one, strictly speaking, to make a
subplot(111). Let's look at the details.
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
Well formatted ticks are an important part of publishing-ready figures.
Matplotlib provides a totally configurable system for ticks. There are
tick locators to specify where ticks should appear and tick formatters to
give ticks the appearance you want. Major and minor ticks can be
located and formatted independently from each other. Per default
minor ticks are not shown, i.e. there is only an empty list for them
because it is as NullLocator (see below).
Tick Locators
There are several locators for different kind of requirements:
Class Description
NullLocator No ticks.
IndexLocator Place a tick on every multiple of some base number of points
plotted.
FixedLocator Tick locations are fixed.
LinearLocator Determine the tick locations.
MultipleLocatorSet a tick on every integer that is multiple of some base.
AutoLocator Select no more than n intervals at nice locations.
LogLocator Determine the tick locations for log axes.
All of these locators derive from the base class
matplotlib.ticker.Locator. You can make your own locator deriving
from it. Handling dates as ticks can be especially tricky. Therefore,
matplotlib provides special locators in matplotlib.dates.
Other Types of Plots
Hints
You need to use the fill_between
command.
Hints
Color is given by angle of (X,Y).
Regular Plots
Starting from the
code below, try to
reproduce the
graphic on the right
taking care of filled
areas:
from pylab import *
n = 256X = np.linspace(-np.pi,np.pi,n,endpoint=True)Y = np.sin(2*X)
plot (X, Y+1, color='blue', alpha=1.00)plot (X, Y-1, color='blue', alpha=1.00)show()
Click on figure for solution.
Scatter Plots
Starting from the
code below, try to
reproduce the
graphic on the right
taking care of marker
size, color and
transparency.
from pylab import *
n = 1024X = np.random.normal(0,1,n)Y = np.random.normal(0,1,n)
scatter(X,Y)show()
Click on figure for solution.
Hints
You need to take care of text
alignment.
Hints
You need to use the clabel
command.
Bar Plots
Starting from the
code below, try to
reproduce the
graphic on the right
by adding labels for
red bars.
from pylab import *
n = 12X = np.arange(n)Y1 = (1-X/float(n)) * np.random.uniform(0.5,1.0,n)Y2 = (1-X/float(n)) * np.random.uniform(0.5,1.0,n)
bar(X, +Y1, facecolor='#9999ff', edgecolor='white')bar(X, -Y2, facecolor='#ff9999', edgecolor='white')
for x,y in zip(X,Y1): text(x+0.4, y+0.05, '%.2f' % y, ha='center', va= 'bottom')
ylim(-1.25,+1.25)show()
Click on figure for solution.
Contour Plots
Starting from the
code below, try to
reproduce the
graphic on the right
taking care of the
colormap (see
Colormaps below).
from pylab import *
def f(x,y): return (1-x/2+x**5+y**3)*np.exp(-x**2-y**2)
n = 256x = np.linspace(-3,3,n)y = np.linspace(-3,3,n)X,Y = np.meshgrid(x,y)
contourf(X, Y, f(X,Y), 8, alpha=.75, cmap='jet')
Hints
You need to take care of the
origin of the image in the
imshow command and use a
colorbar
Hints
You need to modify Z.
C = contour(X, Y, f(X,Y), 8, colors='black', linewidth=.5)show()
Click on figure for solution.
Imshow
Starting from the
code below, try to
reproduce the
graphic on the right
taking care of
colormap, image
interpolation and
origin.
from pylab import *
def f(x,y): return (1-x/2+x**5+y**3)*np.exp(-x**2-y**2)
n = 10x = np.linspace(-3,3,4*n)y = np.linspace(-3,3,3*n)X,Y = np.meshgrid(x,y)imshow(f(X,Y)), show()
Click on figure for solution.
Pie Charts
Starting from the
code below, try to
reproduce the
graphic on the right
taking care of colors
and slices size.
from pylab import *
n = 20Z = np.random.uniform(0,1,n)pie(Z), show()
Click on figure for solution.
Hints
You need to draw arrows twice.
Quiver Plots
Starting from the
code above, try to
reproduce the
graphic on the right
taking care of colors
and orientations.
from pylab import *
n = 8X,Y = np.mgrid[0:n,0:n]quiver(X,Y), show()
Click on figure for solution.
Grids
Starting from the
code below, try to
reproduce the
graphic on the right
taking care of line
styles.
from pylab import *
axes = gca()axes.set_xlim(0,4)axes.set_ylim(0,3)axes.set_xticklabels([])axes.set_yticklabels([])
show()
Click on figure for solution.
Multi Plots
Hints
You can use several subplots
with different partition.
Hints
You only need to modify the
axes line
Starting from the
code below, try to
reproduce the
graphic on the right.
from pylab import *
subplot(2,2,1)subplot(2,2,3)subplot(2,2,4)
show()
Click on figure for
solution.
Polar Axis
Starting from the
code below, try to
reproduce the
graphic on the right.
from pylab import *
axes([0,0,1,1])
N = 20theta = np.arange(0.0, 2*np.pi, 2*np.pi/N)radii = 10*np.random.rand(N)width = np.pi/4*np.random.rand(N)bars = bar(theta, radii, width=width, bottom=0.0)
for r,bar in zip(radii, bars): bar.set_facecolor( cm.jet(r/10.)) bar.set_alpha(0.5)
show()
Click on figure for solution.
3D Plots
Starting from the code below, try to reproduce the graphic on the right.
from pylab import *
Hints
You need to use contourf
Hints
Have a look at the matplotlib
logo.
from mpl_toolkits.mplot3d import Axes3D
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()
Click on figure for solution.
Text
Try to do the same
from scratch !
Click on figure for
solution.
Beyond this tutorial
Matplotlib benefits from extensive documentation as well as a large
community of users and developpers. Here are some links of interest:
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:
>>> from pylab import *>>> help(plot)Help on function plot in module matplotlib.pyplot:
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::
plot(x, y) # plot x and y using default line style and color plot(x, y, 'bo') # plot x and y using blue circle markers plot(y) # plot y using x as index array 0..N-1 plot(y, 'r+') # ditto, but with red plusses
If *x* and/or *y* is 2-dimensional, then the corresponding columns will be plotted. ...
Galleries
The matplotlib gallery is also incredibly useful when you search how
to render a given graphic. Each example comes with its source.
A smaller gallery is also available here.
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
Property Description Appearance
alpha (or a) alpha
transparency on 0-
1 scale
antialiased True or False - use
antialised
rendering
color (or c) matplotlib color
arg
linestyle (or ls) see Line
properties
linewidth (or lw) float, the line
width in points
solid_capstyle Cap style for solid
lines
solid_joinstyle Join style for solid
lines
dash_capstyle Cap style for
dashes
dash_joinstyle Join style for
dashes
marker see Markers
markeredgewidth
(mew)
line width around
the marker symbol
markeredgecolor
(mec)
edge color if a
marker is used
markerfacecolor
(mfc)
face color if a
marker is used
markersize (ms) size of the marker
in points
Line styles
Symbol Description Appearance
- solid line
-- dashed line
-. dash-dot line
: dotted line
. points
, pixels
o circle
^ triangle up
v triangle down
< triangle left
> triangle right
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
Symbol Description Appearance
0 tick left
1 tick right
2 tick up
3 tick down
4 caret left
5 caret right
6 caret up
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
All colormaps can be reversed by appending _r. For instance, gray_r is
the reverse of gray.
If you want to know more about colormaps, checks Documenting the
matplotlib 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
Basic Beginners’ Introduction to plotting in Python
Sarah Blyth
July 23, 2009
1 Introduction
Welcome to a very short introduction on getting started with plotting in Python!I would highly recommend that you refer to the official Matplotlib documentationwhich can be found at:http://matplotlib.sourceforge.net/contents.html.You can also download the Matplotlib manual from the Astronomy Department Vularepository (faster) or directly from the Matplotlib website (slower).
There are all sorts of examples and further very important and useful detailslisted and explained there. The aim of this document is merely to start you off onDay 1 - how to make a plot from scratch.
2 Getting started - what do you need?
You need to have the following installed on your computer to be able to make niceplots.
• Python
• Numpy - this is the module which does most array and mathematical manip-ulation
• Matplotlib - this is the module you will be using for plotting
You can check these are installed by going to a terminal and typing:
$ python>>> import numpy as np>>> import pylab as pl
If you get no errors, then they are installed. If they are not installed, speak to thedepartment SysAdmin to help you install them.You can also check which versions you have installed by doing:
1
$ python>>> import numpy>>> numpy.__version__
The output you get should look something like:
’1.2.1’
Typing:
>>> import matplotlib>>> matplotlib.__version__
should give you something like:
’0.98.5.2’
3 Basic plots
Two basic plot types which you will find are used very often are (x,y) line and scatterplots and histograms. Some code for making these two types of plots is included inthis section.
3.1 Line and scatter plots
3.1.1 Line plots
A common type of graph to plot is a line relating x-values to particular y-values.The code to draw the graph in Fig. 1 is below:
****************************************************# lineplot.py
import numpy as npimport pylab as pl
# Make an array of x valuesx = [1, 2, 3, 4, 5]# Make an array of y values for each x valuey = [1, 4, 9, 16, 25]
# use pylab to plot x and ypl.plot(x, y)
# show the plot on the screenpl.show()****************************************************
2
Figure 1: Line plot made with lineplot.py
3.1.2 Scatter plots
Alternatively, you may want to plot quantities which have an x and y position. Forexample, plotting the location of stars or galaxies in a field for example such as theplot in Fig. 2. Try running the script below to do this:
****************************************************# scatterplot.py
import numpy as npimport pylab as pl
# Make an array of x valuesx = [1, 2, 3, 4, 5]# Make an array of y values for each x valuey = [1, 4, 9, 16, 25]
# use pylab to plot x and y as red circlespl.plot(x, y, ’ro’)
# show the plot on the screenpl.show()****************************************************
3
Figure 2: Plot made with scatterplot.py
3.2 Making things look pretty
3.2.1 Changing the line color
It is very useful to be able to plot more than one set of data on the same axes and tobe able to differentiate between them by using different line and marker styles andcolours. You can specify the colour by inserting a 3rd parameter into the plot()command. For example, in lineplot.py, try changing the line
pl.plot(x, y)
to
pl.plot(x, y, ’r’)
This should give you the same line as before, but it should now be red.The other colours you can easily use are:
character colorb blueg greenr redc cyanm magentay yellowk blackw white
4
3.2.2 Changing the line style
You can also change the style of the line e.g. to be dotted, dashed, etc. Try:
plot(x,y, ’--’)
This should give you a dashed line now.Other linestyles you can use can be found on the Matplotlib webpage http://matplotlib.sourceforge.net/api/pyplot api.html#matplotlib.pyplot.plot.
3.2.3 Changing the marker style
Lastly, you can also vary the marker style you use. Try:
plot(x,y, ’b*’)
This should give you blue star-shaped markers. The table below gives some moreoptions for setting marker types:
’s’ square marker’p’ pentagon marker’*’ star marker’h’ hexagon1 marker’H’ hexagon2 marker’+’ plus marker’x’ x marker’D’ diamond marker’d’ thin diamond marker
3.2.4 Plot and axis titles and limits
It is very important to always label the axes of plots to tell the viewer what they arelooking at. You can do this in python by using the commands:
pl.xlabel(’put text here’)pl.ylabel(’put text here’)
You can make a title for your plot by:
pl.title(’Put plot title here’)
You can change the x and y ranges displayed on your plot by:
pl.xlim(x_low, x_high)pl.ylim(y_low, y_high)
Have a look at the modified macro lineplotAxis.py below:
5
****************************************************#lineplotAxis.py
import numpy as npimport pylab as pl
# Make an array of x valuesx = [1, 2, 3, 4, 5]# Make an array of y values for each x valuey = [1, 4, 9, 16, 25]
# use pylab to plot x and ypl.plot(x, y)
# give plot a titlepl.title(’Plot of y vs. x’)
# make axis labelspl.xlabel(’x axis’)pl.ylabel(’y axis’)
# set axis limitspl.xlim(0.0, 7.0)pl.ylim(0.0, 30.)
# show the plot on the screenpl.show()
****************************************************
This should give you the plot shown in Fig. 3.
3.2.5 Plotting more than one plot on the same set of axes
It is very easy to plot more than one plot on the same axes. You just need to definethe x and y arrays for each of your plots and then:
plot(x1, y1, ’r’)plot(x2, y2, ’g’)
Check out this macro, lineplot2Plots.py and the resulting Fig. 4.
****************************************************#lineplot2Plots.py
import numpy as npimport pylab as pl
6
Figure 3: Plot made with lineplotAxis.py
# Make x, y arrays for each graphx1 = [1, 2, 3, 4, 5]y1 = [1, 4, 9, 16, 25]
x2 = [1, 2, 4, 6, 8]y2 = [2, 4, 8, 12, 16]
# use pylab to plot x and ypl.plot(x1, y1, ’r’)pl.plot(x2, y2, ’g’)
# give plot a titlepl.title(’Plot of y vs. x’)# make axis labelspl.xlabel(’x axis’)pl.ylabel(’y axis’)
# set axis limitspl.xlim(0.0, 9.0)pl.ylim(0.0, 30.)
# show the plot on the screenpl.show()****************************************************
7
Figure 4: Plot made with lineplot2Plots.py
3.2.6 Figure legends
It’s very useful to add legends to plots to differentiate between the different lines orquantities being plotted. In python you can make a legend as follows:
pl.legend((plot1, plot2), (’label1, label2’), ’best’, numpoints=1)
The first parameter is a list of the plots you want labelled. The second parameter isthe list of labels. The third parameter is where you would like matplotlib to placeyour legend. Other optiions are:‘upper right’, ‘upper left’, ‘center’, ‘lower left’, ‘lower right’.‘best’ means that matplotlib will try to choose the position on your plot where thelegend will interfere least with what is plotted (i.e. avoid overlaps etc.).Have a look at Fig. 5 which is made using the macro below:
****************************************************# lineplotFigLegend.py
import numpy as npimport pylab as pl
# Make x, y arrays for each graphx1 = [1, 2, 3, 4, 5]y1 = [1, 4, 9, 16, 25]
x2 = [1, 2, 4, 6, 8]y2 = [2, 4, 8, 12, 16]
8
# use pylab to plot x and y : Give your plots namesplot1 = pl.plot(x1, y1, ’r’)plot2 = pl.plot(x2, y2, ’go’)
# give plot a titlepl.title(’Plot of y vs. x’)# make axis labelspl.xlabel(’x axis’)pl.ylabel(’y axis’)
# set axis limitspl.xlim(0.0, 9.0)pl.ylim(0.0, 30.)
# make legendpl.legend([plot1, plot2], (’red line’, ’green circles’), ’best’, numpoints=1)
# show the plot on the screenpl.show()****************************************************
Figure 5: Plot made with lineplotFigLegend.py
3.3 Histograms
Histograms are very often used in science applications and it is highly likely thatyou will need to plot them at some point! They are very useful to plot distributions
9
e.g. what is the distribution of galaxy velocities in my sample? etc. In Matplotlibyou use the hist command to make a histogram. Take a look at the short macrobelow which makes the plot shown in Fig. 6:
****************************************************# histplot.py
import numpy as npimport pylab as pl
# make an array of random numbers with a gaussian distribution with# mean = 5.0# rms = 3.0# number of points = 1000data = np.random.normal(5.0, 3.0, 1000)
# make a histogram of the data arraypl.hist(data)
# make plot labelspl.xlabel(’data’)
pl.show()****************************************************
If you don’t want to see the black outlines between the bars in the histogram,try:
pl.hist(data, histtype=’stepfilled’)
This is how you make the plot in Fig. 7.
Figure 6: Plot made withhistplot.py
Figure 7: Plot made withhistplot.py
10
3.3.1 Setting the width of the histogram bins manually
You can also set the width of your histogram bins yourself. Try adding the followinglines to the macro histplot.py and you should get the plot shown in Fig. 8.
bins = np.arange(-5., 16., 1.)pl.hist(data, bins, histtype=’stepfilled’)
Figure 8: Manually setting the bin width for a histogram
4 Plotting more than one plot per canvas
Matplotlib is reasonably flexible about allowing multiple plots per canvas and it iseasy to set this up. You need to first make a figure and then specify subplots asfollows:
fig1 = pl.figure(1)pl.subplot(211)
subplot(211) means that you will have a figure with 2 rows, 1 column, and you’regoing to draw in the top plot as shown in Fig. 9. If you want to plot something inthe lower section (as shown in Fig. 10), then you do:
pl.subplot(212)
You can play around with plotting a variety of layouts. For example, Fig. 11 iscreated using the following commands:
11
Figure 9: Showing subplot(211) Figure 10: Showing subplot(212)
f1 = pl.figure(1)pl.subplot(221)pl.subplot(222)pl.subplot(212)
Figure 11: Playing with subplot
You can play with the sizes of the margins and gaps between the subplots using thecommand:
pl.subplots_adjust(left=0.08, right=0.95, wspace=0.25, hspace=0.45)
12
5 Plotting data contained in files
Often you will have data in ascii (text) format which you will need to plot in someway. In this section we will briefly discuss how to open, read from, and write to,files.
5.1 Reading data from ascii files
There are many ways to read data from a file in python. Here I am going to illus-trate one simple method, but you should read the Python, Numpy and Matplotlibmanuals to find out about the other ways which might sometimes apply better toyou particular situation.You can use Numpy to read in numerical values from a text file. For example, let’stake the text file called fakedata.txt which contains the following data (2 columnsof numbers):
****************************************************# fakedata.txt0 01 12 43 94 165 256 367 498 649 810 01 12 43 94 165 256 367 498 649 81****************************************************
We can read this into a numpy 2D array and plot the second column against thefirst using the macro readFileAndPlot.py and shown in Fig. 12:
****************************************************#readFileAndPlot.py
import numpy as np
13
import pylab as pl
# Use numpy to load the data contained in the file# ’fakedata.txt’ into a 2-D array called datadata = np.loadtxt(’fakedata.txt’)
# plot the first column as x, and second column as ypl.plot(data[:,0], data[:,1], ’ro’)pl.xlabel(’x’)pl.ylabel(’y’)pl.xlim(0.0, 10.)
pl.show()****************************************************
Figure 12: Plotting data from a file
5.2 Writing data to a text file
There are also various ways to write text to a text file. Here we show you one possibleway to do it.You first have to open a file to write to, then write what you want to the file, andthen, do not forget to close the file! See the macro below, writeToFile.py to seehow to do this:
****************************************************# writeToFile.py
14
import numpy as np
# Let’s make 2 arrays (x, y) which we will write to a file
# x is an array containing numbers 0 to 10, with intervals of 1x = np.arange(0.0, 10., 1.)# y is an array containing the values in x, squaredy = x*x
print ’x = ’, xprint ’y = ’, y
# Now open a file to write the data to# ’w’ means open for ’writing’file = open(’testdata.txt’, ’w’)
# loop over each line you want to write to filefor i in range(len(x)):
# make a string for each line you want to write# ’\t’ means ’tab’# ’\n’ means ’newline’# ’str()’ means you are converting the quantity in brackets to a string typetxt = str(x[i]) + ’\t’ + str(y[i]) + ’ \n’# write the txt to the filefile.write(txt)
# Close your filefile.close()****************************************************
You should then check that the file you created looks as you would expect! Aquick way to do this on the Linux/Unix terminal command line is:
$ more testdata.txt
This command will print out the contents of your file to the screen and you willquickly be able to check if things look right!
15
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
MatplotlibA tutorial
Devert AlexandreSchool of Software Engineering of USTC
30 November 2012 — Slide 1/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Table of Contents
1 First steps
2 Curve plots
3 Scatter plots
4 Boxplots
5 Histograms
6 Usage example
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 2/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Curve plot
Let’s plot a curve
impor t mathimpor t ma t p l o t l i b . p yp l o t as p l t
# Genera te a s i n u s o i dnbSamples = 256xRange = (−math . p i , math . p i )
x , y = [ ] , [ ]f o r n i n x range ( nbSamples ) :
k = (n + 0 . 5 ) / nbSamplesx . append ( xRange [ 0 ] + ( xRange [ 1 ] − xRange [ 0 ] ) ∗ k )y . append (math . s i n ( x [−1]))
# P lo t the s i n u s o i dp l t . p l o t ( x , y )p l t . show ( )
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 3/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Curve plot
This will show you something like this
4 3 2 1 0 1 2 3 41.0
0.5
0.0
0.5
1.0
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 4/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
numpy
matplotlib can work with numpy arrays
impor t mathimpor t numpyimpor t ma t p l o t l i b . p yp l o t as p l t
# Genera te a s i n u s o i dnbSamples = 256xRange = (−math . p i , math . p i )
x , y = numpy . z e r o s ( nbSamples ) , numpy . z e r o s ( nbSamples )f o r n i n x range ( nbSamples ) :
k = (n + 0 . 5 ) / nbSamplesx [ n ] = xRange [ 0 ] + ( xRange [ 1 ] − xRange [ 0 ] ) ∗ ky [ n ] = math . s i n ( x [ n ] )
# P lo t the s i n u s o i dp l t . p l o t ( x , y )p l t . show ( )
numpy provides a lot of function and is efficient
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 5/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
numpy
• zeros build arrays filled of 0
• linspace build arrays filled with an arithmeticsequence
impor t mathimpor t numpyimpor t ma t p l o t l i b . p yp l o t as p l t
# Genera te a s i n u s o i dx = numpy . l i n s p a c e (−math . p i , math . p i , num=256)y = numpy . z e r o s ( nbSamples )f o r n i n x range ( nbSamples ) :
y [ n ] = math . s i n ( x [ n ] )
# P lo t the s i n u s o i dp l t . p l o t ( x , y )p l t . show ( )
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 6/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
numpy
numpy functions can work on entire arrays
impor t mathimpor t numpyimpor t ma t p l o t l i b . p yp l o t as p l t
# Genera te a s i n u s o i dx = numpy . l i n s p a c e (−math . p i , math . p i , num=256)y = numpy . s i n ( x )
# P lo t the s i n u s o i dp l t . p l o t ( x , y )p l t . show ( )
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 7/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
PDF output
Exporting to a PDF file is just one change
impor t mathimpor t numpyimpor t ma t p l o t l i b . p yp l o t as p l t
# Genera te a s i n u s o i dx = numpy . l i n s p a c e (−math . p i , math . p i , num=256)y = numpy . s i n ( x )
# P lo t the s i n u s o i dp l t . p l o t ( x , y )p l t . s a v e f i g ( ’ s i n−p l o t . pdf ’ , t r a n s p a r e n t=True )
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 8/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Table of Contents
1 First steps
2 Curve plots
3 Scatter plots
4 Boxplots
5 Histograms
6 Usage example
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 9/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Multiple curves
It’s often convenient to show several curves in one figure
impor t mathimpor t numpyimpor t ma t p l o t l i b . p yp l o t as p l t
# Genera te a s i n u s o i d and a c o s i n o i dx = numpy . l i n s p a c e (−math . p i , math . p i , num=256)y = numpy . s i n ( x )z = numpy . cos ( x )
# P lo t the cu r v e sp l t . p l o t ( x , y )p l t . p l o t ( x , z )p l t . show ( )
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 10/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Multiple curves
It’s often convenient to show several curves in one figure
4 3 2 1 0 1 2 3 41.0
0.5
0.0
0.5
1.0
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 10/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Custom colors
Changing colors can help to make nice documents
impor t mathimpor t numpyimpor t ma t p l o t l i b . p yp l o t as p l t
# Genera te a s i n u s o i d and a c o s i n o i dx = numpy . l i n s p a c e (−math . p i , math . p i , num=256)y = numpy . s i n ( x )z = numpy . cos ( x )
# P lo t the cu r v e sp l t . p l o t ( x , y , c=’#FF4500 ’ )p l t . p l o t ( x , z , c=’#4682B4 ’ )p l t . show ( )
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 11/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Custom colors
Changing colors can help to make nice documents
4 3 2 1 0 1 2 3 41.0
0.5
0.0
0.5
1.0
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 11/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Line thickness
Line thickness can be changed as well
impor t mathimpor t numpyimpor t ma t p l o t l i b . p yp l o t as p l t
# Genera te a s i n u s o i d and a c o s i n o i dx = numpy . l i n s p a c e (−math . p i , math . p i , num=256)y = numpy . s i n ( x )z = numpy . cos ( x )
# P lo t the cu r v e sp l t . p l o t ( x , y , l i n ew i d t h =3, c=’#FF4500 ’ )p l t . p l o t ( x , z , c=’#4682B4 ’ )p l t . show ( )
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 12/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Line thickness
Line thickness can be changed as well
4 3 2 1 0 1 2 3 41.0
0.5
0.0
0.5
1.0
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 12/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Line patterns
For printed document, colors can be replaced by linepatterns
impor t mathimpor t numpyimpor t ma t p l o t l i b . p yp l o t as p l t
# L i n e s t y l e s can be ’− ’ , ’−−’, ’− . ’ , ’ : ’
# Genera te a s i n u s o i d and a c o s i n o i dx = numpy . l i n s p a c e (−math . p i , math . p i , num=256)y = numpy . s i n ( x )z = numpy . cos ( x )
# P lo t the cu r v e sp l t . p l o t ( x , y , l i n e s t y l e=’−− ’ , c=’#000000 ’ )p l t . p l o t ( x , z , c=’#808080 ’ )p l t . show ( )
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 13/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Line patternsFor printed document, colors can be replaced by linepatterns
4 3 2 1 0 1 2 3 41.0
0.5
0.0
0.5
1.0
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 13/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Markers
It sometime relevant to show the data points
impor t mathimpor t numpyimpor t ma t p l o t l i b . p yp l o t as p l t
# Markers can be ’ . ’ , ’ , ’ , ’ o ’ , ’ 1 ’ and more
# Genera te a s i n u s o i d and a c o s i n o i dx = numpy . l i n s p a c e (−math . p i , math . p i , num=64)y = numpy . s i n ( x )z = numpy . cos ( x )
# P lo t the cu r v e sp l t . p l o t ( x , y , marker=’ 1 ’ , ma r k e r s i z e =15, c=’#000000 ’ )p l t . p l o t ( x , z , c=’#000000 ’ )p l t . show ( )
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 14/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Markers
It sometime relevant to show the data points
4 3 2 1 0 1 2 3 41.0
0.5
0.0
0.5
1.0
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 14/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Legend
A legend can help to make self–explanatory figures
impor t mathimpor t numpyimpor t ma t p l o t l i b . p yp l o t as p l t
# l egend l o c a t i o n can be ’ b e s t ’ , ’ c e n t e r ’ , ’ l e f t ’ , ’ r i g h t ’ , e t c .
# Genera te a s i n u s o i d and a c o s i n o i dx = numpy . l i n s p a c e (−math . p i , math . p i , num=256)y = numpy . s i n ( x )z = numpy . cos ( x )
# P lo t the cu r v e sp l t . p l o t ( x , y , c=’#FF4500 ’ , l a b e l= ’ s i n ( x ) ’ )p l t . p l o t ( x , z , c=’#4682B4 ’ , l a b e l=’ cos ( x ) ’ )p l t . l e g end ( l o c=’ b e s t ’ )p l t . show ( )
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 15/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Legend
A legend can help to make self–explanatory figures
4 3 2 1 0 1 2 3 41.0
0.5
0.0
0.5
1.0
sin(x)cos(x)
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 15/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Custom axis scaleChanging the axis scale can improve readability
impor t mathimpor t numpyimpor t ma t p l o t l i b . p yp l o t as p l t
# l egend l o c a t i o n can be ’ b e s t ’ , ’ c e n t e r ’ , ’ l e f t ’ , ’ r i g h t ’ , e t c .
# Genera te a s i n u s o i d and a c o s i n o i dx = numpy . l i n s p a c e (−math . p i , math . p i , num=256)y = numpy . s i n ( x )z = numpy . cos ( x )
# Ax i s s e tupf i g = p l t . f i g u r e ( )a x i s = f i g . a dd subp l o t (111)
a x i s . s e t y l i m (−0.5 ∗ math . p i , 0 . 5 ∗ math . p i )
# P lo t the cu r v e sp l t . p l o t ( x , y , c=’#FF4500 ’ , l a b e l= ’ s i n ( x ) ’ )p l t . p l o t ( x , z , c=’#4682B4 ’ , l a b e l=’ cos ( x ) ’ )p l t . l e g end ( l o c=’ b e s t ’ )p l t . show ( )
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 16/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Custom axis scale
Changing the axis scale can improve readability
4 3 2 1 0 1 2 3 41.5
1.0
0.5
0.0
0.5
1.0
1.5sin(x)cos(x)
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 16/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
GridSame goes for a grid, can be helpful
impor t mathimpor t numpyimpor t ma t p l o t l i b . p yp l o t as p l t
# l egend l o c a t i o n can be ’ b e s t ’ , ’ c e n t e r ’ , ’ l e f t ’ , ’ r i g h t ’ , e t c .
# Genera te a s i n u s o i d and a c o s i n o i dx = numpy . l i n s p a c e (−math . p i , math . p i , num=256)y = numpy . s i n ( x )z = numpy . cos ( x )
# Ax i s s e tupf i g = p l t . f i g u r e ( )a x i s = f i g . a dd subp l o t (111)
a x i s . s e t y l i m (−0.5 ∗ math . p i , 0 . 5 ∗ math . p i )a x i s . g r i d ( True )
# P lo t the cu r v e sp l t . p l o t ( x , y , c=’#FF4500 ’ , l a b e l= ’ s i n ( x ) ’ )p l t . p l o t ( x , z , c=’#4682B4 ’ , l a b e l=’ cos ( x ) ’ )p l t . l e g end ( l o c=’ b e s t ’ )p l t . show ( )
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 17/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Grid
Same goes for a grid, can be helpful
4 3 2 1 0 1 2 3 41.5
1.0
0.5
0.0
0.5
1.0
1.5sin(x)cos(x)
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 17/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Error bars
Your data might come with a known measure error
impor t mathimpor t numpyimpor t numpy . randomimpor t ma t p l o t l i b . p yp l o t as p l t
# Genera te a n o i s y s i n u s o i dx = numpy . l i n s p a c e (−math . p i , math . p i , num=48)y = numpy . s i n ( x + 0.05 ∗ numpy . random . s t anda rd no rma l ( l e n ( x ) ) )y e r r o r = 0 .1 ∗ numpy . random . s t anda rd no rma l ( l e n ( x ) )
# Ax i s s e tupf i g = p l t . f i g u r e ( )a x i s = f i g . a dd subp l o t (111)
a x i s . s e t y l i m (−0.5 ∗ math . p i , 0 . 5 ∗ math . p i )
# P lo t the cu r v e sp l t . p l o t ( x , y , c=’#FF4500 ’ )p l t . e r r o r b a r ( x , y , y e r r=y e r r o r )p l t . show ( )
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 18/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Error bars
Your data might come with a known measure error
4 3 2 1 0 1 2 3 41.5
1.0
0.5
0.0
0.5
1.0
1.5
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 18/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Table of Contents
1 First steps
2 Curve plots
3 Scatter plots
4 Boxplots
5 Histograms
6 Usage example
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 19/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Scatter plot
A scatter plot just shows one point for each dataset entry
impor t numpyimpor t numpy . randomimpor t ma t p l o t l i b . p yp l o t as p l t
# Genera te a 2d normal d i s t r i b u t i o nnbPo in t s = 100x = numpy . random . s t anda rd no rma l ( nbPo in t s )y = numpy . random . s t anda rd no rma l ( nbPo in t s )
# P lo t the p o i n t sp l t . s c a t t e r ( x , y )p l t . show ( )
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 20/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Scatter plotA scatter plot just shows one point for each dataset entry
3 2 1 0 1 2 34
3
2
1
0
1
2
3
4
5
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 20/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Aspect ratio
If can be very important to have the same scale on bothaxis
impor t numpyimpor t numpy . randomimpor t ma t p l o t l i b . p yp l o t as p l t
# Genera te a 2d normal d i s t r i b u t i o nnbPo in t s = 100x = numpy . random . s t anda rd no rma l ( nbPo in t s )y = 0 .1 ∗ numpy . random . s t anda rd no rma l ( nbPo in t s )
# Ax i s s e tupf i g = p l t . f i g u r e ( )a x i s = f i g . a dd subp l o t (111 , a sp e c t=’ equa l ’ )
# P lo t the p o i n t sp l t . s c a t t e r ( x , y , c=’#FF4500 ’ )p l t . show ( )
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 21/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Aspect ratioIf can be very important to have the same scale on bothaxis
3 2 1 0 1 2 30.30.20.10.00.10.20.3
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 21/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Aspect ratioAlternative way to keep the same scale on both axis
impor t numpyimpor t numpy . randomimpor t ma t p l o t l i b . p yp l o t as p l t
# Genera te a 2d normal d i s t r i b u t i o nnbPo in t s = 100x = numpy . random . s t anda rd no rma l ( nbPo in t s )y = 0 .1 ∗ numpy . random . s t anda rd no rma l ( nbPo in t s )
# Ax i s s e tupf i g = p l t . f i g u r e ( )a x i s = f i g . a dd subp l o t (111)
cmin , cmax = min (min ( x ) , min ( y ) ) , max(max( x ) , max( y ) )cmin −= 0.05 ∗ ( cmax − cmin )cmax += 0.05 ∗ ( cmax − cmin )
a x i s . s e t x l i m ( cmin , cmax )a x i s . s e t y l i m ( cmin , cmax )
# P lo t the p o i n t sp l t . s c a t t e r ( x , y , c=’#FF4500 ’ )p l t . show ( )
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 22/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Aspect ratio
Alternative way to keep the same scale on both axis
2 1 0 1 2
2
1
0
1
2
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 22/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Multiple scatter plotsAs for curve, you can show 2 datasets on one figure
impor t numpyimpor t numpy . randomimpor t ma t p l o t l i b . p yp l o t as p l t
c o l o r s = ( ’#FF4500 ’ , ’#3CB371 ’ , ’#4682B4 ’ , ’#DB7093 ’ , ’#FFD700 ’ )
# Genera te a 2d normal d i s t r i b u t i o nnbPo in t s = 100
x , y = [ ] , [ ]
x += [ numpy . random . s t anda rd no rma l ( nbPo in t s ) ]y += [ 0 . 2 5 ∗ numpy . random . s t anda rd no rma l ( nbPo in t s ) ]
x += [ 0 . 5 ∗ numpy . random . s t anda rd no rma l ( nbPo in t s ) + 3 . 0 ]y += [2 ∗ numpy . random . s t anda rd no rma l ( nbPo in t s ) + 2 . 0 ]
# Ax i s s e tupf i g = p l t . f i g u r e ( )a x i s = f i g . a dd subp l o t (111 , a sp e c t=’ equa l ’ )
# P lo t the p o i n t sf o r i i n x range ( l e n ( x ) ) :
p l t . s c a t t e r ( x [ i ] , y [ i ] , c=c o l o r s [ i % l e n ( c o l o r s ) ] )
p l t . show ( )
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 23/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Multiple scatter plots
As for curve, you can show 2 datasets on one figure
3 2 1 0 1 2 3 4 54
2
0
2
4
6
8
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 23/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Showing centersIt can help to see the centers or the median points
impor t numpyimpor t numpy . randomimpor t ma t p l o t l i b . p yp l o t as p l t
c o l o r s = ( ’#FF4500 ’ , ’#3CB371 ’ , ’#4682B4 ’ , ’#DB7093 ’ , ’#FFD700 ’ )
# Genera te a 2d normal d i s t r i b u t i o nnbPo in t s = 100
x , y = [ ] , [ ]
x += [ numpy . random . s t anda rd no rma l ( nbPo in t s ) ]y += [ 0 . 2 5 ∗ numpy . random . s t anda rd no rma l ( nbPo in t s ) ]
x += [ 0 . 5 ∗ numpy . random . s t anda rd no rma l ( nbPo in t s ) + 3 . 0 ]y += [2 ∗ numpy . random . s t anda rd no rma l ( nbPo in t s ) + 2 . 0 ]
# Ax i s s e tupf i g = p l t . f i g u r e ( )a x i s = f i g . a dd subp l o t (111 , a sp e c t=’ equa l ’ )
# P lo t the p o i n t sf o r i i n x range ( l e n ( x ) ) :
c o l = c o l o r s [ i % l e n ( c o l o r s ) ]p l t . s c a t t e r ( x [ i ] , y [ i ] , c=c o l )p l t . s c a t t e r ( [ numpy . median ( x [ i ] ) ] , [ numpy . median ( y [ i ] ) ] , c=co l , s=250)
p l t . show ( )
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 24/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Showing centers
It can help to see the centers or the median points
3 2 1 0 1 2 3 4 54
2
0
2
4
6
8
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 24/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Marker stylesYou can use different markers styles
impor t numpyimpor t numpy . randomimpor t ma t p l o t l i b . p yp l o t as p l t
markers = ( ’+’ , ’ ˆ ’ , ’ . ’ )
# Genera te a 2d normal d i s t r i b u t i o nnbPo in t s = 100
x , y = [ ] , [ ]
x += [ numpy . random . s t anda rd no rma l ( nbPo in t s ) ]y += [ 0 . 2 5 ∗ numpy . random . s t anda rd no rma l ( nbPo in t s ) ]
x += [ 0 . 5 ∗ numpy . random . s t anda rd no rma l ( nbPo in t s ) + 3 . 0 ]y += [2 ∗ numpy . random . s t anda rd no rma l ( nbPo in t s ) + 2 . 0 ]
# Ax i s s e tupf i g = p l t . f i g u r e ( )a x i s = f i g . a dd subp l o t (111 , a sp e c t=’ equa l ’ )
# P lo t the p o i n t sf o r i i n x range ( l e n ( x ) ) :m = markers [ i % l e n ( markers ) ]p l t . s c a t t e r ( x [ i ] , y [ i ] , marker=m, c=’#000000 ’ )p l t . s c a t t e r ( [ numpy . median ( x [ i ] ) ] , [ numpy . median ( y [ i ] ) ] , marker=m, s=250 , c=’#000000 ’ )
p l t . show ( )
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 25/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Marker styles
You can use different markers styles
4 3 2 1 0 1 2 3 4 54
2
0
2
4
6
8
10
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 25/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Table of Contents
1 First steps
2 Curve plots
3 Scatter plots
4 Boxplots
5 Histograms
6 Usage example
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 26/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Boxplots
Let’s do a simple boxplot
impor t numpyimpor t numpy . randomimpor t ma t p l o t l i b . p yp l o t as p l t
# Genera te normal d i s t r i b u t i o n datax = numpy . random . s t anda rd no rma l (256)
# Show a boxp l o t o f the datap l t . b o xp l o t ( x )p l t . show ( )
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 27/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Boxplots
Let’s do a simple boxplot
13
2
1
0
1
2
3
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 27/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Boxplots
You might want to show the original data in the sametime
impor t numpyimpor t numpy . randomimpor t ma t p l o t l i b . p yp l o t as p l t
# Genera te normal d i s t r i b u t i o n datax = numpy . random . s t anda rd no rma l (256)
# Show a boxp l o t o f the datap l t . s c a t t e r ( [ 0 ] ∗ l e n ( x ) , x , c=’#4682B4 ’ )p l t . b o xp l o t ( x , p o s i t i o n s =[0 ] )p l t . show ( )
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 28/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
BoxplotsYou might want to show the original data in the sametime
04
3
2
1
0
1
2
3
4
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 28/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Multiple boxplots
Boxplots are often used to show side by side variousdistributions
impor t numpyimpor t numpy . randomimpor t ma t p l o t l i b . p yp l o t as p l t
# Genera te normal d i s t r i b u t i o n datadata = [ ]f o r i i n x range ( 5 ) :
mu = 10 ∗ numpy . random . random sample ( )s igma = 2 ∗ numpy . random . random sample ( ) + 0 .1data . append (numpy . random . normal (mu, sigma , 256))
# Show a boxp l o t o f the datap l t . b o xp l o t ( data )p l t . show ( )
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 29/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Multiple boxplotsBoxplots are often used to show side by side variousdistributions
1 2 3 4 52
4
6
8
10
12
14
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 29/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Orientation
Changing the orientation is easily done
impor t numpyimpor t numpy . randomimpor t ma t p l o t l i b . p yp l o t as p l t
# Genera te normal d i s t r i b u t i o n datadata = [ ]f o r i i n x range ( 5 ) :
mu = 10 ∗ numpy . random . random sample ( )s igma = 2 ∗ numpy . random . random sample ( ) + 0 .1data . append (numpy . random . normal (mu, sigma , 256))
# Show a boxp l o t o f the datap l t . b o xp l o t ( data , v e r t =0)p l t . show ( )
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 30/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Orientation
Changing the orientation is easily done
6 4 2 0 2 4 6 8 10 12
1
2
3
4
5
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 30/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
LegendGood graphics have a proper legend
impor t numpyimpor t numpy . randomimpor t ma t p l o t l i b . p yp l o t as p l t
# Genera te normal d i s t r i b u t i o n datal a b e l s = [ ’ mercury ’ , ’ l e a d ’ , ’ l i t h i um ’ , ’ t ung s t ene ’ , ’ cadnium ’ ]data = [ ]f o r i i n x range ( l e n ( l a b e l s ) ) :
mu = 10 ∗ numpy . random . random sample ( ) + 100sigma = 2 ∗ numpy . random . random sample ( ) + 0 .1data . append (numpy . random . normal (mu, sigma , 256))
# Ax i s s e tupf i g = p l t . f i g u r e ( )a x i s = f i g . a dd subp l o t (111)
a x i s . s e t t i t l e ( ’ A l i e n nodu l e s compos i t i on ’ )xt ickNames = p l t . s e t p ( a x i s , x t i c k l a b e l s = l a b e l s )a x i s . s e t y l a b e l ( ’ c o n c e n t r a t i o n (ppm) ’ )
# Show a boxp l o t o f the datap l t . b o xp l o t ( data )p l t . show ( )
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 31/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Legend
Good graphics have a proper legend
mercury lead lithium tungstene cadnium100
102
104
106
108
110
112co
nce
ntr
ati
on (
ppm
)Alien nodules composition
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 31/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Table of Contents
1 First steps
2 Curve plots
3 Scatter plots
4 Boxplots
5 Histograms
6 Usage example
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 32/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Histograms
Histogram are convenient to sum-up results
impor t numpyimpor t numpy . randomimpor t ma t p l o t l i b . p yp l o t as p l t
# Some datadata = numpy . abs (numpy . random . s t anda rd no rma l ( 30 ) )
# Show an h i s tog ramp l t . barh ( range ( l e n ( data ) ) , data , c o l o r=’#4682B4 ’ )p l t . show ( )
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 33/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Histograms
Histogram are convenient to sum-up results
0.0 0.5 1.0 1.5 2.0 2.50
5
10
15
20
25
30
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 33/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Histograms
A variant to show 2 quantities per item on 1 figure
impor t numpyimpor t numpy . randomimpor t ma t p l o t l i b . p yp l o t as p l t
# Some datadata = [ [ ] , [ ] ]f o r i i n x range ( l e n ( data ) ) :
data [ i ] = numpy . abs (numpy . random . s t anda rd no rma l ( 30 ) )
# Show an h i s tog raml a b e l s = range ( l e n ( data [ 0 ] ) )
p l t . barh ( l a b e l s , data [ 0 ] , c o l o r=’#4682B4 ’ )p l t . barh ( l a b e l s , −1 ∗ data [ 1 ] , c o l o r=’#FF4500 ’ )p l t . show ( )
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 34/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Histograms
A variant to show 2 quantities per item on 1 figure
3 2 1 0 1 2 30
5
10
15
20
25
30
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 34/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
LabelsVery often, we need to name items on an histogram
impor t numpyimpor t numpy . randomimpor t ma t p l o t l i b . p yp l o t as p l t
# Some datanames = [ ’Wang Bu ’ , ’ Cheng Cao ’ , ’ Zhang Xue L i ’ , ’ Tang Wei ’ , ’ Sun Wu Kong ’ ]marks = 7 ∗ numpy . random . random sample ( l e n ( names ) ) + 3
# Ax i s s e tupf i g = p l t . f i g u r e ( )a x i s = f i g . a dd subp l o t (111)
a x i s . s e t x l i m (0 , 10)
p l t . y t i c k s ( numpy . a range ( l e n ( marks ) )+0.5 , names )
a x i s . s e t t i t l e ( ’ Data−mining marks ’ )a x i s . s e t x l a b e l ( ’mark ’ )
# Show an h i s tog ramp l t . barh ( range ( l e n ( marks ) ) , marks , c o l o r=’#4682B4 ’ )p l t . show ( )
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 35/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Labels
Very often, we need to name items on an histogram
0 2 4 6 8 10mark
Wang Bu
Cheng Cao
Zhang Xue Li
Tang Wei
Sun Wu Kong
Data-mining marks
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 35/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Error barsError bars, to indicate the accuracy of values
impor t numpyimpor t numpy . randomimpor t ma t p l o t l i b . p yp l o t as p l t
# Some datanames = [ ’ 6809 ’ , ’ 6502 ’ , ’ 8086 ’ , ’ Z80 ’ , ’RCA1802 ’ ]speed = 70 ∗ numpy . random . random sample ( l e n ( names ) ) + 30e r r o r = 9 ∗ numpy . random . random sample ( l e n ( names ) ) + 1
# Ax i s s e tupf i g = p l t . f i g u r e ( )a x i s = f i g . a dd subp l o t (111)
p l t . y t i c k s ( numpy . a range ( l e n ( names ))+0.5 , names )
a x i s . s e t t i t l e ( ’ 8 b i t s CPU benchmark − s t r i n g t e s t ’ )a x i s . s e t x l a b e l ( ’ s c o r e ’ )
# Show an h i s tog ramp l t . barh ( range ( l e n ( names ) ) , speed , x e r r=e r r o r , c o l o r=’#4682B4 ’ )p l t . show ( )
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 36/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Error bars
Error bars, to indicate the accuracy of values
0 20 40 60 80 100score
6809
6502
8086
Z80
RCA1802
8 bits CPU benchmark - string test
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 36/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Table of Contents
1 First steps
2 Curve plots
3 Scatter plots
4 Boxplots
5 Histograms
6 Usage example
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 37/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Old Faithful
Let’s display some real data: Old Faithful geyser
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 38/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Old Faithful
This way works, but good example of half-done job
impor t numpyimpor t ma t p l o t l i b . p yp l o t as p l t
# Read the datadata = numpy . l o a d t x t ( ’ . / d a t a s e t s / g e y s e r . dat ’ )
# Ax i s s e tupf i g = p l t . f i g u r e ( )a x i s = f i g . a dd subp l o t (111 , a sp e c t=’ equa l ’ )
# P lo t the p o i n t sp l t . s c a t t e r ( data [ : , 0 ] , data [ : , 1 ] , c=’#FF4500 ’ )p l t . show ( )
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 39/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Old Faithful
This way works, but good example of half-done job
30 40 50 60 70 80 90 1001.52.02.53.03.54.04.55.05.5
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 39/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Old Faithful
Let’s make a more readable figure
impor t numpyimpor t ma t p l o t l i b . p yp l o t as p l t
# Read the datadata = numpy . l o a d t x t ( ’ . / d a t a s e t s / g e y s e r . dat ’ )
# Ax i s s e tupf i g = p l t . f i g u r e ( )a x i s = f i g . a dd subp l o t (111)
a x i s . s e t t i t l e ( ’ Old F a i t h f u l g e y s e r d a t a s e t ’ )a x i s . s e t x l a b e l ( ’ w a i t i n g t ime (mn . ) ’ )a x i s . s e t y l a b e l ( ’ e r u p t i o n du r a t i o n (mn . ) ’ )
# P lo t the p o i n t sp l t . s c a t t e r ( data [ : , 0 ] , data [ : , 1 ] , c=’#FF4500 ’ )p l t . show ( )
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 40/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Old Faithful
Let’s make a more readable figure
30 40 50 60 70 80 90 100waiting time (mn.)
1.5
2.0
2.5
3.0
3.5
4.0
4.5
5.0
5.5eru
pti
on d
ura
tion (
mn.)
Old Faithful geyser dataset
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 40/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Mercury & fishes
Let’s display more complex data: fishes and mercurypoisoning
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 41/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Mercury & fishes
A first try
impor t numpyimpor t ma t p l o t l i b . p yp l o t as p l t
# Read the datadata = numpy . l o a d t x t ( ’ . / d a t a s e t s / f i s h . dat ’ )
# Ax i s s e tupf i g = p l t . f i g u r e ( )a x i s = f i g . a dd subp l o t (111)
a x i s . s e t t i t l e ( ’ North Ca r o l i n a f i s h e s mercury c o n c e n t r a t i o n ’ )a x i s . s e t x l a b e l ( ’ we ight ( g . ) ’ )a x i s . s e t y l a b e l ( ’ mercury c o n c e n t r a t i o n (ppm) ’ )
# P lo t the p o i n t sp l t . s c a t t e r ( data [ : , 3 ] , data [ : , 4 ] , c=’#FF4500 ’ )p l t . show ( )
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 42/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Mercury & fishes
A first try
1000 0 1000 2000 3000 4000 5000weight (g.)
0.5
0.0
0.5
1.0
1.5
2.0
2.5
3.0
3.5
4.0m
erc
ury
conce
ntr
ati
on (
ppm
)North Carolina fishes mercury concentration
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 42/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Mercury & fishes
Show more information with subplots
20 30 40 50 60 70length (cm.)
10000
10002000300040005000
weig
ht
(g.)
1000 0 1000 2000 3000 4000 5000weight (g.)
0.50.00.51.01.52.02.53.03.54.0
merc
ury
conce
ntr
ati
on (
ppm
)
20 30 40 50 60 70length (cm.)
0.50.00.51.01.52.02.53.03.54.0
merc
ury
conce
ntr
ati
on (
ppm
)North Carolina fishes mercury concentration
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 43/44
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC
Mercury & fishes
Data from one river with its own color
20 30 40 50 60 70length (cm.)
10000
10002000300040005000
weig
ht
(g.)
1000 0 1000 2000 3000 4000 5000weight (g.)
0.50.00.51.01.52.02.53.03.54.0
merc
ury
conce
ntr
ati
on (
ppm
)
20 30 40 50 60 70length (cm.)
0.50.00.51.01.52.02.53.03.54.0
merc
ury
conce
ntr
ati
on (
ppm
)North Carolina fishes mercury concentration
Devert Alexandre (School of Software Engineering of USTC) — Matplotlib — Slide 44/44
Scientific Plotting with Matplotlib
A Tutorial at PyCon US 2012
March 8, 2012 Santa Clara, CA, USA
author: Dr.-Ing. Mike Müller
email: [email protected]
version: 1.1
© Python Academy 2012 Page 1
Contents1 Introduction 4
2 IPython 4
3 pylab 4
4 Simple Plots 4
4.1 Exercises 7
5 Properties 7
5.1 Exercise 9
6 Text 10
6.1 Exercise 11
7 Ticks 11
7.1 Where and What 11
7.2 Tick Locators 11
7.3 Tick Formatters 12
7.4 Exercises 13
8 Figures, Subplots, and Axes 13
8.1 The Hierarchy 13
8.2 Figures 13
8.3 Subplots 14
8.4 Axes 15
8.5 Exercises 15
9 Other Types of Plots 15
9.1 Many More 15
9.2 Bar Charts 15
9.3 Horizontal Bar Charts 16
9.4 Broken Horizontal Bar Charts 16
9.5 Box and Whisker Plots 17
9.6 Contour Plots 17
9.7 Histograms 18
9.8 Loglog Plots 19
9.9 Pie Charts 19
9.10 Polar Plots 20
9.11 Arrow Plots 20
© Python Academy 2012 Page 2
9.12 Scatter Plots 21
9.13 Sparsity Pattern Plots 21
9.14 Stem Plots 22
9.15 Date Plots 22
10 The Class Library 23
10.1 The Figure Class 23
10.2 The Classes Axes and Subplot 24
10.3 Other Classes 24
10.4 Example 24
10.5 Exercises 25
11 Creating New Plot Types 25
11.1 Exercises 27
12 Animations 28
12.1 Exercises 30
© Python Academy 2012 Page 3
1 Introductionmatplotlib is probably the single most used Python package for 2D-graphics. It provides both a very quickway to visualize data from Python and publication-quality figures in many formats. We are going to explorematplotlib in interactive mode covering most common cases. We also look at the class library which isprovided with an object-oriented interface.
2 IPythonIPython is an enhanced interactive Python shell that has lots of interesting features including named inputsand outputs, access to shell commands, improved debugging and many more. When we start it with thecommand line argument -pylab, it allows interactive matplotlib sessions that hasMatlab/Mathematica-like functionality.
3 pylabpylab provides a procedural interface to the matplotlib object-oriented plotting library. It is modeledclosely after Matlab(TM). Therefore, the majority of plotting commands in pylab has Matlab(TM) analogswith similar arguments. Important commands are explained with interactive examples.
4 Simple PlotsLet's start an interactive session:
$python ipython.py -pylab
This brings us to the IPython prompt:
IPython 0.8.1 -- An enhanced Interactive Python.? -> Introduction to IPython's features.%magic -> Information about IPython's 'magic' % functions.help -> Python's own help system.object? -> Details about 'object'. ?object also works, ?? prints more.
Welcome to pylab, a matplotlib-based Python environment.For more information, type 'help(pylab)'.
In [1]:
Now we can make our first, really simple plot:
In [1]: plot(range(10))Out[1]: [<matplotlib.lines.Line2D instance at 0x01AA26E8>]
In [2]:
The numbers form 0 through 9 are plotted:
1 Introduction
© Python Academy 2012 Page 4
Now we can interactively add features to or plot:
In [2]: xlabel('measured')Out[2]: <matplotlib.text.Text instance at 0x01A9D210>
In [3]: ylabel('calculated')Out[3]: <matplotlib.text.Text instance at 0x01A9D918>
In [4]: title('Measured vs. calculated')Out[4]: <matplotlib.text.Text instance at 0x01A9DF80>
In [5]: grid(True)
In [6]:
We get a reference to our plot:
In [6]: my_plot = gca()
and to our line we plotted, which is the first in the plot:
In [7]: line = my_plot.lines[0]
Now we can set properties using set_something methods:
In [8]: line.set_marker('o')
or the setp function:
In [9]: setp(line, color='g')Out[9]: [None]
1 Introduction
© Python Academy 2012 Page 5
To apply the new properties we need to redraw the screen:
In [10]: draw()
We can also add several lines to one plot:
In [1]: x = arange(100)
In [2]: linear = arange(100)
In [3]: square = [v * v for v in arange(0, 10, 0.1)]
In [4]: lines = plot(x, linear, x, square)
Let's add a legend:
In [5]: legend(('linear', 'square'))Out[5]: <matplotlib.legend.Legend instance at 0x01BBC170>
This does not look particularly nice. We would rather like to have it at the left. So we clean the old graph:
In [6]: clf()
and print it anew providing new line styles (a green dotted line with crosses for the linear and a red dashedline with circles for the square graph):
In [7]: lines = plot(x, linear, 'g:+', x, square, 'r--o')
Now we add the legend at the upper left corner:
In [8]: l = legend(('linear', 'square'), loc='upper left')
The result looks like this:
1 Introduction
© Python Academy 2012 Page 6
4.1 Exercises
1. Plot a simple graph of a sinus function in the range 0 to 3 with a step size of 0.01.
2. Make the line red. Add diamond-shaped markers with size of 5.
3. Add a legend and a grid to the plot.
5 PropertiesSo far we have used properties for the lines. There are three possibilities to set them:
1) as keyword arguments at creation time: plot(x, linear, 'g:+', x, square, 'r--o').
2. with the function setp: setp(line, color='g').
3. using the set_something methods: line.set_marker('o')
Lines have several properties as shown in the following table:
Property Value
alpha alpha transparency on 0-1 scale
antialiased True or False - use antialised rendering
color matplotlib color arg
data_clipping whether to use numeric to clip data
label string optionally used for legend
linestyle one of - : -. -
linewidth float, the line width in points
marker one of + , o . s v x > <, etc
markeredgewidth line width around the marker symbol
4.1 Exercises
© Python Academy 2012 Page 7
markeredgecolor edge color if a marker is used
markerfacecolor face color if a marker is used
markersize size of the marker in points
There are many line styles that can be specified with symbols:
Symbol Description
- solid line
-- dashed line
-. dash-dot line
: dotted line
. points
, pixels
o circle symbols
^ triangle up symbols
v triangle down symbols
< triangle left symbols
> triangle right symbols
s square symbols
+ plus symbols
x cross symbols
D diamond symbols
d thin diamond symbols
1 tripod down symbols
2 tripod up symbols
3 tripod left symbols
4 tripod right symbols
h hexagon symbols
H rotated hexagon symbols
p pentagon symbols
| vertical line symbols
_ horizontal line symbols
steps use gnuplot style 'steps' # kwarg only
Colors can be given in many ways: one-letter abbreviations, gray scale intensity from 0 to 1, RGB in hex andtuple format as well as any legal html color name.
4.1 Exercises
© Python Academy 2012 Page 8
The one-letter abbreviations are very handy for quick work. With following you can get quite a few thingsdone:
Abbreviation Color
b blue
g green
r red
c cyan
m magenta
y yellow
k black
w white
Other objects also have properties. The following table list the text properties:
Property Value
alpha alpha transparency on 0-1 scale
color matplotlib color arg
family set the font family, eg 'sans-serif', 'cursive', 'fantasy'
fontangle the font slant, one of 'normal', 'italic', 'oblique'
horizontalalignment 'left', 'right' or 'center'
multialignment 'left', 'right' or 'center' only for multiline strings
name font name, eg, 'Sans', 'Courier', 'Helvetica'
position x,y location
variant font variant, eg 'normal', 'small-caps'
rotation angle in degrees for rotated text
size fontsize in points, eg, 8, 10, 12
style font style, one of 'normal', 'italic', 'oblique'
text set the text string itself
verticalalignment 'top', 'bottom' or 'center'
weight font weight, e.g. 'normal', 'bold', 'heavy', 'light'
5.1 Exercise
1. Apply different line styles to a plot. Change line color and thickness as well as the size and the kind ofthe marker. Experiment with different styles.
5.1 Exercise
© Python Academy 2012 Page 9
6 TextWe've already used some commands to add text to our figure: xlabel ylabel, and title.
There are two functions to put text at a defined position. text adds the text with data coordinates:
In [2]: plot(arange(10))In [3]: t1 = text(5, 5, 'Text in the middle')
figtext uses figure coordinates form 0 to 1:
In [4]: t2 = figtext(0.8, 0.8, 'Upper right text')
matplotlib supports TeX mathematical expression. So r'$\pi$' will show up as:¼\pi
If you want to get more control over where the text goes, you use annotations:
In [4]: ax.annotate('Here is something special', xy = (1, 1))
We will write the text at the position (1, 1) in terms of data. There are many optional arguments that help tocustomize the position of the text. The arguments textcoords and xycoords specifies what x and ymean:
argument coordinate system
'figure points' points from the lower left corner of the figure
'figure pixels' pixels from the lower left corner of the figure
'figure fraction' 0,0 is lower left of figure and 1,1 is upper, right
'axes points' points from lower left corner of axes
'axes pixels' pixels from lower left corner of axes
6 Text
© Python Academy 2012 Page 10
'axes fraction' 0,1 is lower left of axes and 1,1 is upper right
'data' use the axes data coordinate system
If we do not supply xycoords, the text will be written at xy.
Furthermore, we can use an arrow whose appearance can also be described in detail:
In [14]: plot(arange(10))Out[14]: [<matplotlib.lines.Line2D instance at 0x01BB15D0>]
In [15]: ax = gca()
In [16]: ax.annotate('Here is something special', xy = (2, 1), xytext=(1,5))Out[16]: <matplotlib.text.Annotation instance at 0x01BB1648>
In [17]: ax.annotate('Here is something special', xy = (2, 1), xytext=(1,5), ....: arrowprops={'facecolor': 'r'})
6.1 Exercise
1. Annotate a line at two places with text. Use green and red arrows and align it according to figurepoints and data.
7 Ticks
7.1 Where and WhatWell formated ticks are an important part of publishing-ready figures. matplotlib provides a totallyconfigurable system for ticks. There are tick locators to specify where ticks should appear and tick formattersto make ticks look like the way you want. Major and minor ticks can be located and formated independentlyfrom each other. Per default minor ticks are not shown, i.e. there is only an empty list for them because it is asNullLocator (see below).
7.2 Tick LocatorsThere are several locators for different kind of requirements:
Class Description
NullLocator no ticks
IndexLocator locator for index plots (e.g. where x = range(len(y))
LinearLocator evenly spaced ticks from min to max
LogLocator logarithmically ticks from min to max
MultipleLocator ticks and range are a multiple of base; either integer or float
AutoLocator choose a MultipleLocator and dynamically reassign
6.1 Exercise
© Python Academy 2012 Page 11
All of these locators derive from the base class matplotlib.ticker.Locator. You can make your ownlocator deriving from it.
Handling dates as ticks can be especially tricky. Therefore, matplotlib provides special locatorsin ``matplotlib.dates:
Class Description
MinuteLocator locate minutes
HourLocator locate hours
DayLocator locate specified days of the month
WeekdayLocator locate days of the week, e.g. MO, TU
MonthLocator locate months, e.g. 10 for October
YearLocator locate years that are multiples of base
RRuleLocator locate using a matplotlib.dates.rrule
7.3 Tick FormattersSimilarly to locators, there are formatters:
Class Description
NullFormatter no labels on the ticks
FixedFormatter set the strings manually for the labels
FuncFormatter user defined function sets the labels
FormatStrFormatter use a sprintf format string
IndexFormatter cycle through fixed strings by tick position
ScalarFormatter default formatter for scalars; autopick the fmt string
LogFormatter formatter for log axes
DateFormatter use an strftime string to format the date
All of these formatters derive from the base class matplotlib.ticker.Formatter. You can make yourown formatter deriving from it.
Now we set our major locator to 2 and the minor locator to 1. We also format the numbers as decimals usingthe FormatStrFormatter:
In [5]: major_locator = MultipleLocator(2)
In [6]: major_formatter = FormatStrFormatter('%5.2f')
In [7]: minor_locator = MultipleLocator(1)
In [8]: ax.xaxis.set_major_locator(major_locator)
In [9]: ax.xaxis.set_minor_locator(minor_locator)
7.3 Tick Formatters
© Python Academy 2012 Page 12
In [10]: ax.xaxis.set_major_formatter(major_formatter)
In [10]: draw()
After we redraw the figure our x axis should look like this:
7.4 Exercises
1. Plot a graph with dates for one year with daily values at the x axis using the built-in module datetime.
2. Format the dates in such a way that only the first day of the month is shown.
3. Display the dates with and without the year. Show the month as number and as first three letters of themonth name.
8 Figures, Subplots, and Axes
8.1 The HierarchySo far we have used implicit figure and axes creation. This is handy for fast plots. We can have more controlover the display using figure, subplot, and axes explicitly. A figure in matplotlib means the wholewindow in the user interface. Within this figure there can be subplots. While subplot positions the plotsin a regular grid, axes allows free placement within the figure. Both can be useful depending on yourintention. We've already work with figures and subplots without explicitly calling them. When we call plotmatplotlib calls gca() to get the current axes and gca in turn calls gcf() to get the current figure. Ifthere is none it calls figure() to make one, strictly speaking, to make a subplot(111). Let's look at thedetails.
8.2 FiguresA figure is the windows in the GUI that has "Figure #" as title. Figures are numbered starting from 1 asopposed to the normal Python way starting from 0. This is clearly MATLAB-style. There are severalparameters that determine how 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
7.4 Exercises
© Python Academy 2012 Page 13
The defaults can be specified in the resource file and will be used most of the time. Only the number of thefigure 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 canclose 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 asargument).
As with other objects, you can set figure properties also setp or with the set_something methods.
8.3 SubplotsWith subplot you can arrange plots in regular grid. You need to specify the number of rows and columnsand the number of the plot.
A plot with two rows and one column is created with subplot(211) and subplot(212). The result lookslike this:
If you want two plots side by side, you create one row and two columns with subplot(121) andsubplot(112). The result looks like this:
You can arrange as many figures as you want. A two-by-two arrangement can be created withsubplot(221), subplot(222), subplot(223), and subplot(224). The result looks like this:
Frequently, you don't want all subplots to have ticks or labels. You can set the xticklabels or the yticklabels to an empty list ([]). Every subplot defines the methods 'is_first_row, is_first_col,
8.3 Subplots
© Python Academy 2012 Page 14
is_last_row, is_last_col. These can help to set ticks and labels only for the outer pots.
8.4 AxesAxes are very similar to subplots but allow placement of plots at any location in the figure. So if we want to puta smaller plot inside a bigger one we do so with axes:
In [22]: plot(x)Out[22]: [<matplotlib.lines.Line2D instance at 0x02C9CE90>]
In [23]: a = axes([0.2, 0.5, 0.25, 0.25])
In [24]: plot(x)
The result looks like this:
8.5 Exercises
1. Draw two figures, one 5 by 5, one 10 by 10 inches.
2. Add four subplots to one figure. Add labels and ticks only to the outermost axes.
3. Place a small plot in one bigger plot.
9 Other Types of Plots
9.1 Many MoreSo far we have used only line plots. matplotlib offers many more types of plots. We will have a brief lookat some of them. All functions have many optional arguments that are not shown here.
9.2 Bar ChartsThe function bar creates a new bar chart:
bar([1, 2, 3], [4, 3, 7])
Now we have three bars starting at 1, 2, and 3 with height of 4, 3, 7 respectively:
8.4 Axes
© Python Academy 2012 Page 15
The default column width is 0.8. It can be changed with common methods by setting width. As it can becolor and bottom, we can also set an error bar with yerr or xerr.
9.3 Horizontal Bar ChartsThe function barh creates an vertical bar chart. Using the same data:
barh([1, 2, 3], [4, 3, 7])
We get:
9.4 Broken Horizontal Bar ChartsWe can also have discontinuous vertical bars with broken_barh. We specify start and width of the range iny-direction and all start-width pairs in x-direction:
yrange = (2, 1)xranges = ([0, 0.5], [1, 1], [4, 1])broken_barh(xranges, yrange)
We changes the extension of the y-axis to make plot look nicer:
ax = gca()ax.set_ylim(0, 5)(0, 5)draw()
and get this:
9.3 Horizontal Bar Charts
© Python Academy 2012 Page 16
9.5 Box and Whisker PlotsWe can draw box and whisker plots:
boxplot((arange(2, 10), arange(1, 5)))
We want to have the whiskers well within the plot and therefore increase the y axis:
ax = gca()ax.set_ylim(0, 12)draw()
Our plot looks like this:
The range of the whiskers can be determined with the argument whis, which defaults to 1.5. The range of thewhiskers is between the most extreme data point within whis*(75%-25%) of the data.
9.6 Contour PlotsWe can also do contour plots. We define arrays for the x and y coordinates:
x = y = arange(10)
and also a 2D array for z:
z = ones((10, 10))z[5,5] = 7z[2,1] = 3z[8,7] = 4zarray([[ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
9.5 Box and Whisker Plots
© Python Academy 2012 Page 17
[ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [ 1., 3., 1., 1., 1., 1., 1., 1., 1., 1.], [ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [ 1., 1., 1., 1., 1., 7., 1., 1., 1., 1.], [ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [ 1., 1., 1., 1., 1., 1., 1., 4., 1., 1.], [ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.]])
Now we can make a simple contour plot:
contour(x, x, z)
Our plot looks like this:
We can also fill the area. We just use numbers form 0 to 9 for the values v:
v = xcontourf(x, x, z, v)
Now our plot area is filled:
9.7 HistogramsWe can make histograms. Let's get some normally distributed random numbers from numpy:
import numpy as Nr_numbers = N.random.normal(size= 1000)
Now we make a simple histogram:
9.7 Histograms
© Python Academy 2012 Page 18
hist(r_numbers)
With 100 numbers our figure looks pretty good:
9.8 Loglog PlotsPlots with logarithmic scales are easy:
loglog(arange(1000))
We set the mayor and minor grid:
grid(True)grid(True, which='minor')
Now we have loglog plot:
If we want only one axis with a logarithmic scale we can use semilogx or semilogy.
9.9 Pie ChartsPie charts can also be created with a few lines:
data = [500, 700, 300]labels = ['cats', 'dogs', 'other']pie(data, labels=labels)
The result looks as expected:
9.8 Loglog Plots
© Python Academy 2012 Page 19
9.10 Polar PlotsPolar plots are also possible. Let's define our r from 0 to 360 and our theta from 0 to 360 degrees. Weneed to convert them to radians:
r = arange(360)theta = r / (180/pi)
Now plot in polar coordinates:
polar(theta, r)
We get a nice spiral:
9.11 Arrow PlotsPlotting arrows in 2D plane can be achieved with quiver. We define the x and y coordinates of the arrowshafts:
x = y = arange(10)
The x and y components of the arrows are specified as 2D arrays:
u = ones((10, 10))v = ones((10, 10))u[4, 4] = 3v[1, 1] = -1
Now we can plot the arrows:
9.10 Polar Plots
© Python Academy 2012 Page 20
quiver(x, y, u, v)
All arrows point to the upper right, except two. The one at the location (4, 4) has 3 units in x-direction and theother at location (1, 1) has -1 unit in y direction:
9.12 Scatter PlotsScatter plots print x vs. y diagrams. We define x and y and make some point in y random:
x = arange(10)y = arange(10)y[1] = 7y[4] = 2y[8] = 3
Now make a scatter plot:
scatter(x, y)
The three different values for y break out of the line:
9.13 Sparsity Pattern PlotsWorking with sparse matrices, it is often of interest as how the matrix looks like in terms of sparsity. We takean identity matrix as an example:
i = identity(10)iarray([[1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
9.12 Scatter Plots
© Python Academy 2012 Page 21
[0, 0, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 1]])
Now we look at it more visually:
spy(i)
9.14 Stem PlotsStem plots vertical lines at the given x location up to the specified y location. Let's reuse x and y from ourscatter (see above):
stem(x, y)
9.15 Date PlotsThere is a function for creating date plots. Let's define 10 dates starting at January 1st 2000 at 15.dayintervals:
import datetimed1 = datetime.datetime(2000, 1, 1)delta = datetime.timedelta(15)dates = [d1 + x * delta for x in range(1
9.14 Stem Plots
© Python Academy 2012 Page 22
dates[datetime.datetime(2000, 1, 1, 0, 0), datetime.datetime(2000, 1, 16, 0, 0), datetime.datetime(2000, 1, 31, 0, 0), datetime.datetime(2000, 2, 15, 0, 0), datetime.datetime(2000, 3, 1, 0, 0), datetime.datetime(2000, 3, 16, 0, 0), datetime.datetime(2000, 3, 31, 0, 0), datetime.datetime(2000, 4, 15, 0, 0), datetime.datetime(2000, 4, 30, 0, 0), datetime.datetime(2000, 5, 15, 0, 0)]
We reuse our data from the scatter plot (see above):
yarray([0, 7, 2, 3, 2, 5, 6, 7, 3, 9])
Now we can plot the dates at the x axis:
plot_date(dates, y)
10 The Class LibrarySo far we have used the pylab interface only. As the name suggests it is just wrapper around the classlibrary. All pylabb commands can be invoked via the class library using an object-oriented approach.
10.1 The Figure ClassThe class Figure lives in the module matplotlib.figure. Its constructor takes these arguments:
figsize=None, dpi=None, facecolor=None, edgecolor=None,linewidth=1.0, frameon=True, subplotpars=None
Comparing this with the arguments of figure in pylab shows significant overlap:
num=None, figsize=None, dpi=None, facecolor=Noneedgecolor=None, frameon=True
10 The Class Library
© Python Academy 2012 Page 23
Figure provides lots of methods, many of them have equivalents in pylab. The methods add_axes andadd_subplot are called if new axes or subplot are created with axes or subplot in pylab. Also themethod gca maps directly to pylab as do legend, text and many others.
There are also several set_something method such as set_facecolor or set_edgecolor that will becalled through pylab to set properties of the figure. Figure also implements get_something methodssuch as get_axes or get_facecolor to get properties of the figure.
10.2 The Classes Axes and SubplotIn the class Axes we find most of the figure elements such as Axis, Tick, Line2D, or Text. It also sets thecoordinate system. The class Subplot inherits from Axes and adds some more functionality to arrange theplots in a grid.
Analogous to Figure, it has methods to get and set properties and methods already encountered asfunctions in pylab such as annotate. In addition, Axes has methods for all types of plots shown in theprevious section.
10.3 Other ClassesOther classes such as text, Legend or Ticker are setup very similarly. They can be understood mostlyby comparing to the pylab interface.
10.4 ExampleLet's look at an example for using the object-oriented API:
#file matplotlib/oo.py
import matplotlib.pyplot as plt #1
figsize = (8, 5) #2fig = plt.figure(figsize=figsize) #3ax = fig.add_subplot(111) #4line = ax.plot(range(10))[0] #5ax.set_title('Plotted with OO interface') #6ax.set_xlabel('measured')ax.set_ylabel('calculated')ax.grid(True) #7line.set_marker('o') #8
plt.savefig('oo.png', dpi=150) #9plt.show() #10
Since we are not in the interactive pylab-mode, we need to import pyplot (#1). We set the size of our figureto be 8 by 5 inches (#2). Now we initialize a new figure (#3) and add a subplot to the figure (#4). The 111says one plot at position 1, 1 just as in MATLAB. We create a new plot with the numbers from 0 to 9 and atthe same time get a reference to our line (#5). We can add several things to our plot. So we set a title andlabels for the x and y axis (#6). We also want to see the grid (#7) and would like to have little filled circles asmarkers (#8).
10.2 The Classes Axes and Subplot
© Python Academy 2012 Page 24
Finally, we save our figure as a PNG file specifying the desired resolution in dpi (#9) and show our figure onthe screen (#10).
10.5 Exercises
1. Use the object-oriented API of matplotlib to create a png-file with a plot of two lines, one linear andsquare with a legend in it.
11 Creating New Plot TypesWe can come up with our own new plot type. Matplotlib provides all the building blocks to compose new plots.We would like to have a stacked plot, that is lines are drawn on top of each other and the y values representthe difference to the other plot rather than to zero. We implement our own plot type. It assumes all y valuesare positive and the lowest plot will be filled starting from zero, i.e the x axis.
"""A simple stacked plot."""
import matplotlib as mpl #1import matplotlib.pyplot as plt #2import numpy #3
First we need to import matplotlib itself (#1) as well as pyplot (#2) and numpy (#3).
StackPlot(object): #4 """A stacked plot.
Data are stacked on top of each other and the space between the lines is filled with color. """
def __init__(self, x, y_data, axes=None, colors=None, names=None, loc='best'): #5 """Show the plot. """ # We've got plenty of default arguments. # pylint: disable-msg=R0913 # Make sure we can work with numpy arrays. self.x = numpy.array(x) #6 self.y_data = numpy.array(y_data) self.axes = axes if not axes: self.axes = plt.gca() #7 default_colors = ['r', 'b', 'g', 'y', 'm', 'w'] #8 self.colors = colors self.names = names self.loc = loc if not self.colors: #9 # Repeat colors as needed.
10.5 Exercises
© Python Academy 2012 Page 25
ncolors = len(self.y_data) colors = default_colors * (1 + (ncolors // len(default_colors))) self.colors = colors[:ncolors] self.stacked = None self._stack_data()
Now we define a new class StackedPlot (#4). It takes the x values and a two dimensional array of yvalues, where each row will become one plot, as well as a bunch of optional arguments that we will meet later(#5). We convert all data into numpy arrays (#6). This won't hurt if they are arrays already. If no axes wassupplied, we just get the current axes (#7). This is consistent with the behavior of the standard plots. Wedefine some default colors that will be used if none are given in the __init__ (#8). We don't know howmany plots might be stacked. Therefore, we just repeat the default colors again and again until all data have acolor (#9).
def _stack_data(self): #10 """Accumulate data. """ nlines = self.y_data.shape[0] + 1 #11 self.stacked = numpy.zeros((nlines, self.y_data.shape[1])) #12 for index in xrange(1, nlines): self.stacked[index] = (self.stacked[index - 1] + #13 self.y_data[index - 1])
We stack our data (#10). We need one more entry than y values (#11) and the first one is all zeros (#12).Than we just add the new values on top of the ones below (#13).
def draw(self): #14 """Draw the plot. """ for data1, data2, color in zip(self.stacked[:-1], self.stacked[1:], self.colors): #15 self.axes.fill_between(self.x, data1, data2, color=color) #16 self.axes.plot(self.x, data2, 'k', linewidth=0.1) #17 if self.names: rects = [] for color in self.colors: #18 rects.append(plt.Rectangle((0, 0), 1, 1, fc=color)) self.axes.legend(rects, self.names, loc=self.loc, prop=mpl.font_manager.FontProperties(size=10))
We draw our new plot (#14). Using zip, we go through all stacked data each time with a lower and upperboundary as well as through our colors (#15). We fill the space between both plots (#16) and also plot theline in black (#17). Furthermore, we make a nice legend for all colors (#18).
def __getattr__(self, name): #19 """Delegate not found attributes to axes.
This works for set_tile, set_xlabel etc.
10.5 Exercises
© Python Academy 2012 Page 26
""" try: return getattr(self.axes, name) except AttributeError: raise AttributeError("'StackPlot' object has no attribute '%s'" % name)
We delegate all attributes that are not found (#19) to or axes. This allows to provide all theset_<property> methods without actually implementing them.
if __name__ == '__main__':
def test(): #20 """Check if it works. """ x = range(10) #21 y_data = numpy.ones((5, 10), dtype=numpy.float) #22 y_data[1, 1] = 2 y_data[2, 1] = 2 y_data[3, 1] = 2 y_data[1, 2] = 0.5 y_data[2, 3] = 0.5 y_data[3, 4] = 0.5 fig = fig = plt.figure() s_plot = StackPlot(x, y_data, axes=fig.add_subplot(111), #23 names=['a', 'b', 'c', 'd', 'e']) s_plot.set_title('My Stacked Plot') #24 s_plot.set_xlabel('x') s_plot.set_ylabel('y') s_plot.draw() #25 plt.show() #26
test()
Finally, we test our program (#20). We create data for x (#22) and y (#23). We replace some data in y, that isonly ones, with some different numbers. Now we can add our new stacked plot to our axes (#23). Thisargument is optional. Leaving it out, the class will use the current axes. We set some properties (#24), createthe plot (#25) and show our figure (#26).
11.1 Exercises
1. Change some y data in the test function and see how this changes the graph. Increase the number ofstacked plots to 50 and 200. See what happens.
2. Place four stacked plots in one figure. Change the data slightly for each stacked plot.
3. Move the legend to different place for each of the four plots.
11.1 Exercises
© Python Academy 2012 Page 27
12 AnimationsAnimations can be useful to show how things change over time. There are two basic ways to produce ananimation with matplotlib:
1. Saving pixel graphics for each animation frame and stitch them together with tools like imagemagick orffmpeg.
2. Having an animation directly in the figure.
The first approach is straight forward. The second typically needs some interaction with the GUI library. Let'shave a look at an example:
"""Animation with matplolib."""
import random
import matplotlib #1matplotlib.use('TkAgg') #2import matplotlib.pyplot as plt
After importing matplotlib (#1), we need to tell what GUI to use. We use TKinter here (#2). Othersupported tool kits are Qt, wxPython and GTK. The solution presented here is Tkinter specific.
class Residual(object): #3 """Generator for residual values.
This somehow mimics the residual a solver for system of equations would produces. """
def __init__(self, start, limit): #4 self.value = start self.limit = limit self.counter = 0 self.done = False
def __call__(self): #5 if self.done: return None #6 diff = random.random() * self.value #7 if self.counter == 2: #8 self.value += diff self.counter = 0 else: #9 self.value -= diff self.counter += 1 if self.value <= self.limit: #10 self.done = True return self.value
12 Animations
© Python Academy 2012 Page 28
The class Residual (#3) will be used as function that keeps its state. It is a placeholder for a numericalprogram that solves something interactively and is finished if a certain value of the residual is reached. The__int__ (#4) takes the starting value and the limit to be reached. We implement the special method__call__ (#5) making an instance of this class behave just like a function but with the additional feature ofkeeping state information in self. If we are done, the limit was reached, we return None (#6). The differenceleading to a new residual is determined by multiplying the old value with a random number between 0 and 1(#7). We increment the residual by diff once (#8) after decrementing it twice (#9). If the residual is less orequal to the limit, we are done (#10).
class ResidualGraph(object): #11 """Semilog plot with matplotlib.
This plot is updated for every calculation time step. Therefore it grows dynamically. """
def __init__(self, start): # make a figure self.fig = plt.figure() #12 self.axes = self.fig.add_subplot(111) #13 self.counter = 0 #14 self.x = [self.counter] #15 self.y = [start] #16 self.show_initial_graph() #17 self.window = plt.get_current_fig_manager().window #18
The ResidualGraph (#11) is responsible for displaying the animated figure. After creating a new figure(#12) and adding one subplot (#13), we start with a counter of zero (#14) and use it as the first and so faronly value for x (#15). The value makes the first entry in our y values (#16). After initializing the graph, weneed to get a hold of the window (#18). This will be needed to start the animation as wee will see later.
def show_initial_graph(self): """Show a first version of the graph without calculated residuals. """ self.axes.semilogy(self.x, self.y) #19 self.axes.set_title('Solver test program') self.axes.set_xlabel('Number of steps') self.axes.set_ylabel('Nonlinear residual') self.fig.canvas.draw() #20
Initializing the graph is straight forward. We use a semi-log plot (#19). After adding title and labels, we drawour plot (#20).
def update(self, value): #21 """Redraw the graph with an added value for the residual. """ self.counter += 1 #22 self.x.append(self.counter) #23 self.y.append(value) #24
12 Animations
© Python Academy 2012 Page 29
plt.semilogy(self.x, self.y, color='blue') #25 plt.draw() #26
The update-method (#21) is important, because it will redraw the graph for each animation step. Afterincrementing the counter (#22) and adding it to the x values (#23), we append the new residual value toour y values (#24) and make new plot (#25) that we draw (#26).
def start_animation(start, limit): #27 """Start the animation. """
def animate(): #28 """Animation function will be called by GUI library (Tkinter). """ residual = get_residual() #29 # show value and update graph if residual is not None: #30 graph.window.after(300, animate) #31 print residual graph.update(residual) #32 else: print 'done' #33 get_residual = Residual(start, limit) #34 graph = ResidualGraph(start) #35 graph.window.after(300, animate) #36 plt.show() #37
In start_animation (#27), we define a nested function animate (#28). This function will be called byTkinter after a specified amount of time. We get the new value for the residual from get_residual(), whichis an instance of the class Residual (#34). As long as we have a value for the residual (#30), we callwindow.after with a delay of 300 milliseconds and the function animate, i.e. the function we just define(#31). The object window is from Tkinter (#18). We also update the graph (#32) which is an instance ofResidualGraph (#35). The first call to window.after (#36) starts the animation. We also want the plotstay alive after the animation is finished and therefore call show (#37).
if __name__ == '__main__':
start_animation(1e4, 1e-7) #38
Finally, we start everything with some numbers spanning eleven orders of magnitude (#38).
12.1 Exercises
1. Alternate the color of the plotted line with each animation step.
12.1 Exercises
© Python Academy 2012 Page 30
Matplotlibhttp://matplotlib.sourceforge.net/
A python 2D plotting library Publication quality figures in several hardcopy formats and
interactive environments across platforms
Can be used in Python scripts, the Python and IPython shell (a la matlab or mathematica), web application servers, and 6 GUI toolkits
Toolkits (4)http://matplotlib.sourceforge.net/users/toolkits.html E.g., Basemap plots data on map projections (with continental
and political boundaries)
Installation In the Matplotlib homepage, click on the download link
In the download page, click matplotlib-1.3.0.win32-py2.7.exe
Download and install
Under C:\Python26\Lib\site-packages, 2 new foldersmatplotlib
mpl_toolkits
To test, in the Python command line,
type the 1st example (3 lines plotting a straight line) in the Tutorial (see below)
plot() creates an object and outputs info on it
Not an error report
show() displays a figure
Close it to return from the command
Documentation Documentation page (links): http://matplotlib.org/contents.html
PyplotTutorial (8 pp.)http://matplotlib.sourceforge.net/users/pyplot_tutorial.html
User’s Guidehttp://matplotlib.org/users/ Refer to as needed
Cookbook / Matplotlib http://matplotlib.org/api/cbook_api.html Lots of good examples Shows figure, link to page giving code and explanation
Cyrille Rossant, Learning IPython for Interactive Computing and Data Visualization, Packt Publishing, 2013, 138 pages
Amazon $27, 4.5 on 8 reviews
matplotlib FAQhttp://matplotlib.sourceforge.net/faq/index.html
Using matplotlib in a python shellhttp://matplotlib.sourceforge.net/users/shell.html
For performance, by default, matplotlib defers drawing until the end of the
But, to test things out interactively (in the shell), usually want to update after every command
Shows how to do this Do it with IPython
Exampleshttp://matplotlib.org/examples/
Just names under headings, but names are descriptive
The “What's new” pagehttp://matplotlib.org/users/whats_new.html
Every feature ever introduced into matplotlib is listed here under the version that introduced it
Often with a link to an example or documentation
Global Module Index: http://matplotlib.org/py-modindex.html
Documentation on the various modules
This and the next 2 are comprehensive
The Matplotlib API: http://matplotlib.sourceforge.net/api/
Documentation on the various packages
Pyplot documentation (142 pp.): http://matplotlib.org/api/pyplot_api.html
IPythonhttp://ipython.org
Enhanced Python shell for efficient interactive work
Library to build customized interactive environments using Python
System for interactive distributed and parallel computing
“Python Programming Environments: IPython,” UC Davishttp://csc.ucdavis.edu/~chaos/courses/nlp/Software/iPython.html
Simple introduction and some links
Installation and Documentation Under Windows, IPython needs PyReadline to support color, tab
completion, etc.http://ipython.org/pyreadline.html
Download the installer: follow the link and download and run pyreadline-1.7.1.win32.exe
For IPython itself, go to the download page (http://ipython.org/download.html) and click the link for the binary Windows installer for Python 2
The documentation page (http://ipython.org/documentation.html) has links to the manual and lots of other documentation
matplotlib.pyplot vs. pylab Package matplotlib.pyplot provides a MATLAB-like plotting
framework
Package pylab combines pyplot with NumPy into a single namespace
Convenient for interactive work
For programming, it’s recommended that the namespaces be kept separate
See such things as import pylab
Orimport matplotlib.pyplot as plt
The standard alias import numpy as np
The standard alias
Also from pylab import *
Orfrom matplotlib.pyplot import *
from numpy import *
We’ll use from pylab import *
Some examples don’t show this—just assume it
Batch and Interactive Use In a script,
import the names in the pylab namespace
then list the commands
Example: file E:\SomeFolder\mpl1.pyfrom pylab import *plot([1,2,3,4])show()
ExecutingE:\SomeFolder>mpl1.py
produces the figure shown
The command line hangs until the figure is dismissed (click ‘X’ in the upper right)
plot()
Given a single list or array, plot() assumes it’s a vector of y-values
Automatically generates an x vector of the same length with consecutive integers beginning with 0
Here [0,1,2,3]
To override default behavior, supply the x data: plot(x,y )where x and y have equal lengths
show()
Should be called at most once per script
Last line of the script
Then the GUI takes control, rendering the figure
In place of show(), can save the figure to with, say,savefig('fig1.png')
Saved in the same folder as the script
Override this with a full pathname as argument—e.g., savefig('E:\\SomeOtherFolder\\fig1.png')
Supported formats: emf, eps, pdf, png, ps, raw, rgba, svg, svgz
If no extension specified, defaults to .png
Matplotlib from the Shell Using matplotlib in the shell, we see the objects produced
>>> from pylab import *
>>> plot([1,2,3,4])[<matplotlib.lines.Line2D object at 0x01A3EF30>]
>>> show()
Hangs until the figure is dismissed or close() issued
show() clears the figure: issuing it again has no result
If you construct another figure, show() displays it without hanging
draw()
Clear the current figure and initialize a blank figure without hanging or displaying anything
Results of subsequent commands added to the figure >>> draw()
>>> plot([1,2,3])[<matplotlib.lines.Line2D object at 0x01C4B6B0>]
>>> plot([1,2,3],[0,1,2])[<matplotlib.lines.Line2D object at 0x01D28330>]
Shows 2 lines on the figure after show() is invoked
Use close() to dismiss the figure and clear it
clf() clears the figure (also deletes the white background) without dismissing it
Figures saved using savefig() in the shell by default are saved in C:\Python27
Override this by giving a full pathname
Interactive Mode In interactive mode, objects are displayed as soon as they’re created
Use ion() to turn on interactive mode, ioff() to turn it off
Example Import the pylab namespace, turn on interactive mode and plot a line
>>> from pylab import *
>>> ion()
>>> plot([1,2,3,4])[<matplotlib.lines.Line2D object at 0x02694A10>]
A figure appears with this line on it
The command line doesn’t hang
Plot another line >>> plot([4,3,2,1])[<matplotlib.lines.Line2D object at 0x00D68C30>]
This line is shown on the figure as soon as the command is issued
Turn off interactive mode and plot another line>>> ioff()
>>> plot([3,2.5,2,1.5])[<matplotlib.lines.Line2D object at 0x00D09090>]
The figure remains unchanged—no new line
Update the figure >>> show()
The figure now has all 3 lines
The command line is hung until the figure is dismissed
Matplotlib in IPython Recommended way to use matplotlib interactively is with ipython
In the IPython drop-down menu, select pylab
IPython’s pylab mode detects the matplotlibrc file
Makes the right settings to run matplotlib with your GUI of choice in interactive mode using threading
IPython in pylab mode knows enough about matplotlib internals to make all the right settings
Plots items as they’re produce without draw() or show()
Default folder for saving figures on fileC:\Documents and Settings\current user
More Curve Plotting plot() has a format string argument specifying the color and line type
Goes after the y argument (whether or not there’s an x argument)
Can specify one or the other or concatenate a color string with a line style string in either order
Default format string is 'b-' ( solid blue line)
Some color abbreviations b (blue), g (green), r (red), k (black), c (cyan)
Can specify colors in many other ways (e.g., RGB triples)
Some line styles that fill in the line between the specified points - (solid line), -- (dashed line), -. (dash-dot line), : (dotted line)
Some line styles that don’t fill in the line between the specified point o (circles), + (plus symbols), x (crosses), D (diamond symbols)
For a complete list of line styles and format strings, http://matplotlib.sourceforge.net/api/pyplot_api.html#module-matplotlib.pyplot
Look under matplotlib.pyplot.plot()
The axis() command takes a list[xmin, xmax, ymin, ymax]
and specifies the view port of the axes
ExampleIn [1]: plot([1,2,3,4], [1,4,9,16], 'ro')Out[1]: [<matplotlib.lines.Line2D object at 0x034579D0>]
In [2]: axis([0, 6, 0, 20])Out[2]: [0, 6, 0, 20]
Generally work with arrays, not lists
All sequences are converted to NumPy arrays internally
plot() can draw more than one line at a time
Put the (1-3) arguments for one line in the figure
Then the (1-3) arguments for the next line
And so on
Can’t have 2 lines in succession specified just by their y arguments
matplotlib couldn’t tell whether it’s a y then the next y or an x then the corresponding y
The example (next slide) illustrates plotting several lines with different format styles in one command using arrays
In [1]: t = arange(0.0, 5.2, 0.2)
In [2]: plot(t, t, t, t**2, 'rs', t, t**3, 'g^')Out[2]:[<matplotlib.lines.Line2D object at 0x02A6D410>,<matplotlib.lines.Line2D object at 0x02A6D650>,<matplotlib.lines.Line2D object at 0x02A6D8D0>]
Lines you encounter are instances of the Line2D class
Instances have the following properties
Property Values
alpha The alpha transparency on 0-1 scale
antialiased True | False - use antialised rendering
color a matplotlib color arg
label a string optionally used for legend
linestyle One of -- : -. -
linewidth a float, the line width in points
marker One of + , o . s v x > < ^
markeredgewidth The line width around the marker symbol
markeredgecolor The edge color if a marker is used
markerfacecolor The face color if a marker is used
markersize The size of the marker in points
alpha = 0.0 is complete transparency, alpha = 1.0 is complete opacity
One of 3 ways to set line properties: Use keyword line properties as keyword arguments—e.g., plot(x, y, linewidth=2.0)
Another way: Use the setter methods of the Line2D instance
For every property prop, there’s a set_prop() method that takes an update value for that property
To use this, note that plot() returns a list of lines
The following has 1 line with tuple unpacking line, = plot(x, y, 'o')
line.set_antialiased(False)
The 3rd (and final) way to set line properties: use function setp()
1st argument can be an object or sequence of objects
The rest are keyword arguments updating the object’s (or objects’) properties
E.g., lines = plot(x1, y1, x2, y2)
setp(lines, color='r', linewidth=2.0)
Text The text commands are self-explanatory
xlabel()
ylabel()
title()
text()
In simple cases, all but text() take just a string argument
text() needs at least 3 arguments: x and y coordinates (as per the axes) and a string
All take optional keyword arguments or dictionaries to specify the font properties
They return instances of class Text
plot([1,2,3])xlabel('time')ylabel('volts')title('A line')text(0.5, 2.5, 'Hello world!')
The following font properties of Text instances can be set
Property Values
alpha The alpha transparency on 0-1 scale
color a matplotlib color argument
fontangle italic | normal | oblique
fontname Sans | Helvetica | Courier | Times | Others
fontsize a scalar, eg, 10
fontweight normal | bold | light 4
horizontalalignment left | center | right
rotation horizontal | vertical
verticalalignment bottom | center | top
Three ways to specify font properties: using
setp
object oriented methods (We skip this)
font dictionaries
Use setp to set any propertyt = xlabel('time')
setp(t, color='r', fontweight='bold')
Also works with a list of text instances—e.g., labels = getp(gca(), 'xticklabels')
setp(labels, color='r', fontweight='bold')
All text commands take an optional dictionary argument and keyword arguments to control font properties
E.g., to set a default font theme and override individual properties for given text commandsfont = {'fontname' : 'Courier',
'color' : 'r','fontweight' : 'bold','fontsize' : 11}
plot([1,2,3])
title('A title', font, fontsize=12)
text(0.5, 2.5, 'a line', font, color='k')
xlabel('time (s)', font)
ylabel('voltage (mV)', font)
Legends A legend is a box (by default in upper right) associating labels with lines
(displayed as per their formats)legend(lines, labels)
where lines is a tuple of lines, labels a tuple of corresponding strings
from pylab import *lines = plot([1,2,3],'b-',[0,1,2],'r--')legend(lines, ('First','Second'))savefig('legend')
If there’s only 1 line, be sure to include the commas in the tupleslengend((line1,), ('Profit',))
Use keyword argument loc to override the default location
Use predefined strings or integer codes ‘upper right’ 1‘upper left’ 2‘lower left’ 3‘lower right’ 4‘right’ 5‘center left’ 6‘center right’ 7‘lower center’ 8‘upper center’ 9‘center’ 10
E.g., legend((line,), ('Profit',) , loc=2)
Bar Charts Function bar() creates a bar chart
Most of the arguments may be either scalars or sequences
Say in […] what they normally are
Required argumentsleft x coordinates of the left sides of the bars [sequence]height height of the bars [sequence]
Some optional keyword arguments orientation orientation of the bars (‘vertical’ | ‘horizontal’)width width of the bars [scalar]color color of the bars [scalar]xerr if not None,
generates error ticks on top the bars [sequence]yerr if not None,
generates errorbars on top the bars [sequence]ecolor color of any errorbar [scalar]capsize length (in points) of errorbar caps (default 2) [scalar]log False (default) leaves the orientation axis as is,
True sets it to log scale
For the following example, need the following
yticks(seq, labels)
Make the ticks on the y axis at y-values in seq with labels the corresponding elements of labels
Without labels, number as per seq
xticks(seq, labels)
Same, but for the x axis
xlim(xmin, xmax)
The values on the x axis go from xmin to xmax
from pylab import *
labels = ["Baseline", "System"]
data = [3.75, 4.75]
yerror = [0.3497, 0.3108]
xerror = [0.2, 0.2]
xlocations = array(range(len(data)))+0.5
width = 0.5
csize = 10
ec = 'r'
bar(xlocations, data, yerr=yerror, width=width,xerr=xerror, capsize=csize, ecolor=ec)
yticks(range(0, 8))
xticks(xlocations+ width/2, labels)
xlim(0, xlocations[-1]+width*2)
title("Average Ratings on the Training Set")
savefig('bar')
Histogramshist(x, bins=n )
Computes and draws a histogram
x: a sequence of numbers (usually with many repetitions)
If keyword argument bins is an integer, it’s the number of (equally spaced) bins
Default is 10
from pylab import *
import numpy
x = numpy.random.normal(2, 0.5, 1000)
hist(x, bins=50)
savefig('my_hist')
Scatter Plotsscatter(x, y )
x and y are arrays of numbers of the same length, N
Makes a scatter plot of x vs. y
from pylab import *
N = 20
x = 0.9*rand(N)
y = 0.9*rand(N)
scatter(x,y)
savefig('scatter_dem')
Keyword Argumentss
If an integer, size of marks in points2 , i.e., area occupied (default 20)
If an array of length N, gives the sizes of the corresponding elements of x, y
marker
Symbol marking the points (default = ‘o’)
Same options as for lines that don’t connect the dots And a few more
c
A single color or a length-N sequence of colors
from pylab import *
N = 30
x = 0.9*rand(N)
y = 0.9*rand(N)
area = pi * (10 * rand(N))**2 # 0 to 10 point radius
scatter(x,y,s=area, marker='^', c='r')
savefig('scatter_demo')
Odds and EndsHorizontal and Vertical Lineshlines(y, xmin, xmax ) Draw horizontal lines at heights given by the numbers in array y
If xmin and xmax are arrays of same length as y, they give the left and right endpoints of the corresponding lines, resp.
If either is a scalar, all lines have the same endpoint, specified by it
Some keyword arguments linewidth (or lw): line width in points
color: default ‘k’
vlines(x, ymin, ymax ) is similar but for vertical lines
from pylab import *
y = arange(0,3,0.1)
x = 2*y
hlines(y, 0, x, color='b', lw=4)
savefig('hlines')
Axis Lines axhline() draws a line on the x axis spanning the horizontal
extent of the axes
axhline(y) draws such a line parallel to the x axis at height y
Some keyword argumentscolor: default ‘b’
label
linewidth in points
axvline() is similar but w.r.t. the y axis
Grid Lines grid(True) produces grid lines at the tick coordinates
grid(None) suppresses the grid
grid() toggles the presence of the grid
Some keyword arguments color: default ‘k’
linestyle: default ‘:’
linewidth
Some Axes instance methodsget_xgridlines()
get_ygridlines()
Example:setp(gca().get_xgridlines(), color='r')
Resizing the Figure Often should make the figure wider or higher so objects aren’t cramped
Use Figure instance methods get_size_inches() and set_size_inches()
To get an array of the 2 dimensions in inches (width then height):fig = gcf()dsize = fig.get_size_inches()
E.g., to double the widthfig.set_size_inches( 2 * dsize[0], dsize[1] )
See the example in the SciPy Cookbook
http://www.scipy.org/Cookbook/Matplotlib/AdjustingImageSize
Multiple Subplots Functions axes() and subplot() both used to create axes
subplot() used more often
subplot(numRows, numCols, plotNum)
Creates axes in a regular grid of axes numRows by numCols
plotNum becomes the current subplot
Subplots numbered top-down, left-to-right 1 is the 1st number
Commas can be omitted if all numbers are single digit
Subsequent subplot() calls must be consistent on the numbers or rows and columns
subplot() returns a Subplot instance
Subplot is derived from Axes
Can call subplot() and axes() in a subplot
E.g., have multiple axes in 1 subplot
See the Tutorial for subplots sharing axis tick labels
from pylab import *subplot(221)plot([1,2,3])subplot(222)plot([2,3,4])subplot(223)plot([1,2,3], 'r--')subplot(224)plot([2,3,4], 'r--')subplot(221)plot([3,2,1], 'r--')savefig('subplot')
3D Matplotlib: mplot3d See http://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html
An Axes3D object is created like any other axes, but using the projection='3d' keyword
Create a new matplotlib.figure.Figure and add to it a new axes of type Axes3Dimport matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
Example: Line PlotsAxes3D.plot(xs, ys, *args, **kwargs)
Plot 2D or 3D data
xs, ys are the arrays of x, y coordinates of vertices
zs is the z value(s), either 1 for all points or (as array) 1 for each point
zdir gives which direction to use as z (‘x’, ‘y’ or ‘z’) when plotting a 2D set
Other arguments are passed on to plot()
Exampleimport matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
mpl.rcParams['legend.fontsize'] = 10
fig = plt.figure()
ax = fig.gca(projection='3d')
theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
z = np.linspace(-2, 2, 100)
r = z**2 + 1
x = r * np.sin(theta)
y = r * np.cos(theta)
ax.plot(x, y, z, \label='parametric curve')
ax.legend()
plt.show()
AnimationThe Old Way To take an animated plot and turn it into a movie,
save a series of image files (e.g., PNG) and
use an external tool to convert them to a movie
Can use mencoder, part of the mplayer suite
See http://www.mplayerhq.hu/design7/news.html
Can download binaries for Windows
Or use ImageMagick’s convert (“the Swiss army knife of image tools”)
See http://www.imagemagick.org/script/convert.php
Matplotlib Animation Matplotlib Animation Tutorial
http://jakevdp.github.com/blog/2012/08/18/matplotlib-animation-tutorial/
Matplotlib animation documentation http://matplotlib.org/api/animation_api.html
Matplotlib animation examples http://matplotlib.org/examples/animation/
Official and good, but documentation limited to meager program comments The tutorial (above) goes through several of these
Alias http://matplotlib.sourceforge.net/examples/animation/index.html
This replaces the Cookbook exampleshttp://www.scipy.org/Cookbook/Matplotlib/Animations