01 Matplotlib PDF
01 Matplotlib PDF
Stephen Pascoe
March 16, 2014
1.1 Introduction
Matplotlib is an excellent 2D and 3D graphics library for generating scientific figures. Some of the many advantages of this library include:
One of the of the key features of matplotlib that I would like to emphasize, and that I think makes matplotlib
highly suitable for generating figures for scientific publications is that all aspects of the figure can be controlled
programmatically. This is important for reproducibility and convenient when one needs to regenerate the figure
with updated data or change its appearance.
More information at the Matplotlib web page: http://matplotlib.org/To get started using Matplotlib in a Python
program, either include the symbols from the pylab module (the easy way):
In [12]: from pylab import *
or import the matplotlib.pyplot module under the name plt (the tidy way). In this case we will also find
it useful to import the array module numpy.
In [13]: import matplotlib.pyplot as plt
import numpy as np
It is designed to be compatible with MATLABs plotting functions, so it is easy to get started with if you are
familiar with MATLAB.
To use this API from matplotlib, we need to include the symbols in the pylab module:
In [14]: from pylab import *
Most of the plotting related functions in MATLAB are covered by the pylab module. For example, subplot and
color/symbol selection:
In [17]: subplot(1,2,1)
plot(x, y, r--)
subplot(1,2,2)
plot(y, x, g*-)
Out [17]: [<matplotlib.lines.Line2D at 0x10338f190>]
The good thing about the pylab MATLAB-style API is that it is easy to get started with if you are familiar with
MATLAB, and it has a minumum of coding overhead for simple plots.
However, Id encourrage not using the MATLAB compatible API for anything but the simplest figures.
Instead, I recommend learning and using matplotlibs object-oriented plotting API. It is remarkably powerful. For
advanced figures with subplots, insets and other components it is very nice to work with.
Exercise 1.1 : Starting MatPlotlib
Although a little bit more code is involved, the advantage is that we now have full control of where the plot axes
are placed, and we can easily add more than one axis to the figure:
In [19]: fig = plt.figure()
axes1 = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # main axes
axes2 = fig.add_axes([0.2, 0.5, 0.4, 0.3]) # inset axes
# main figure
axes1.plot(x, y, r)
axes1.set_xlabel(x)
axes1.set_ylabel(y)
axes1.set_title(title)
# insert
axes2.plot(y, x, g)
axes2.set_xlabel(y)
axes2.set_ylabel(x)
axes2.set_title(insert title);
2 Saving figures
To save a figure to a file we can use the savefig method in the Figure class:
In [21]: fig.savefig("filename.png")
Here we can also optionally specify the DPI and chose between different output formats. Matplotlib can generate high-quality output in a number formats, including PNG, JPG, EPS, SVG, and PDF. For scientific papers, use PDF whenever possible. (LaTeX documents compiled with pdflatex can include PDFs using the
includegraphics command).
In [28]: # A histogram
n = np.random.randn(100000)
fig, axes = plt.subplots(1, 2, figsize=(12,4))
axes[0].hist(n)
axes[0].set_title("Default histogram")
axes[0].set_xlim((min(n), max(n)))
5 Plotting 2D arrays
Matplotlib provides several methods of plotting functions of 2 variables as a 2D field using colour or contour lines
to represent the function value. We will look at 3 of these methods.
In most of these functions we will use a colormap to encode one dimension of the data. There are a number
of predefined colormaps. It is relatively straightforward to define custom colormaps. For a list of pre-defined
colormaps, see: http://www.scipy.org/Cookbook/Matplotlib/Show_colormaps
In [29]: # Import library of Colour maps
from matplotlib import cm
In [30]: x =
y =
X,Y
Z =
Imshow
Axes.imshow() interprets a 2D array as an image by mapping function values to colours within a colour map.
This method is the easiest way of visualising a 2D array provided each point represents the same sized region in
cartesian space.
By default imshow() uses the array-index values as x and y co-ordinates.
In [31]: fig, axes = plt.subplots(1, 3, figsize=(10, 4))
axes[0].imshow(Z)
axes[1].imshow(Z, cmap=cm.RdBu)
axes[2].imshow(Z, cmap=cm.Set1)
Out [31]: <matplotlib.image.AxesImage at 0x103f1afd0>
Specify an extent of the image enables simple mapping of the array to a region in cartesian coordinates. Also note
you can select different interpolation methods to smooth pixel boundaries.
pcolor
If your grid is not equally spaced in x and y then you cannot use imshow(). Instead you can use
Axes.pcolor() for any rectilinear grids (where all x grid lines are perpendicular y grid lines). Here we
stretch the x and y coordinates and use pcolor() to plot rectangular grid boxes.
In [39]: X2, Y2 = np.meshgrid(x**3, y**3)
fig, ax = plt.subplots(figsize=(7,6))
p = ax.pcolor(X2/(2*pi), Y2/(2*pi), Z, cmap=cm.RdBu)
cb = fig.colorbar(p, ax=ax)
Note: The method Axes.pcolormesh() is even more flexible, allowing rotated and curvilinear grids
contour and contourf
Matplotlibs Axes.contour() and Axes.contourf() methods create contour and filled contour plots respectively.