J. D. Hunter 2007 Matplotlib A 2D Graphics en
J. D. Hunter 2007 Matplotlib A 2D Graphics en
MATPLOTLIB:
A 2D GRAPHICS ENVIRONMENT
By John D. Hunter
Matplotlib is a 2D graphics package used for Python for application development, interactive scripting,
and publication-quality image generation across user interfaces and operating systems.
90 Copublished by the IEEE CS and the AIP 1521-9615/07/$25.00 © 2007 IEEE COMPUTING IN SCIENCE & ENGINEERING
PyLab, which is a simple wrapper of the matplotlib API. Al-
though many die-hard Pythonistas bristle at PyLab’s Mat-
lab-like syntax and its from pylab import * examples,
which dump the PyLab and NumPy functionality into a sin-
gle namespace for ease of use, this feature is an essential sell-
ing point for many teachers whose students aren’t
programmers and don’t want to be: they just want to get up
and running. For many of these students, Matlab is the only
exposure to programming they’ve ever had, and the ability
to leverage that knowledge is often a critical point for teach-
ers trying to bring Python into the science classroom. In Figure 1. The PBrain project. An electrocorticography
Figure 2 , I’ve enabled the usetex parameter in the mat- (ECoG) viewer, written in matplotlib and embedded in a
plotlib configuration file so LaTeX can generate both the pygtk application.
text and the equations.
Let’s look at a sample session from IPython, the interac-
tive Python shell that is matplotlib-aware in PyLab mode
(also see p. 21 in this issue):
In [1]: subplot(111)
In [2]: t = arange(0.0,3.01,0.01)
In [3]: s = sin(2*pi*t)
In [4]: c = sin(4*pi*t)
In [5]: fill(t, s, ‘blue’, t, c, ‘green’,
alpha=0.3);
In [6]: title(r’\TeX\ is
No.$\displaystyle\sum_{n=1}^\infty
\frac{-e^{i\pi}}{2^n}$!’) Figure 2. LaTeX support. Setting the usetex option in the
matplotlib configuration file enables LaTeX generation of
IPython detects which GUI windowing system you want the text and equations in a matplotlib figure, as this
to use by inspecting your matplotlib configuration, imports screenshot shows.
the PyLab namespace, and then makes the necessary thread-
ing calls so you can work interactively with a GUI mainloop
such as GTK’s. neighbor interpolation for those who just want to see their
raw data), “bilinear,” “bicubic,” and 14 other interpolation
Images, Color Mapping, methods for smoothing data. For color mapping, all the clas-
Contouring, and Color Bars sic color maps from Matlab are available (gray, jet, hot,
In addition to simple line plots, you can fairly easily create copper, bone, and so on) as well as scores more. You can
more sophisticated graphs, including color-mapped images also define custom color maps.
with contouring and labeling, in just a few lines of Python. Let’s look at a Python script that computes a bivariate
For pseudocolor images, matplotlib supports various image- Gaussian distribution plotted as a grayscale image and then
interpolation and color-mapping schemes. For interpola- overlays contour lines using the heated object scale hot
tion, you can choose “nearest” (which does a nearest color map:
MAY/JUNE 2007 91
SCIENTIFIC PROGRAMMING
MAY/JUNE 2007 93
SCIENTIFIC PROGRAMMING
fig = Figure()
canvas = FigureCanvas(fig)
ax = fig.add_subplot(111)
ax.plot([1,2,3])
fig.savefig(‘agg_demo.png’)
Figure 4. Low-resolution satellite view of the Earth using To create a different output format, such as PostScript, we
the matplotlib basemap toolkit. Higher-resolution political need only change the first line to from matplotlib.back-
and geographic boundaries, as well as a wealth of map ends.backend_ps import FigureCanvasPS as Fig-
projections, are available as configuration options in the ureCanvas. The method canvas.draw() in our code
toolkit. example creates a back-end-specific renderer and forwards
the draw call to Figure. The draw method looks like this:
Circulation: Computing in Science & Engineering (ISSN 1521-9615) is published bimonthly by the AIP and the IEEE Computer Society. IEEE Headquarters,
Three Park Ave., 17th Floor, New York, NY 10016-5997; IEEE Computer Society Publications Office, 10662 Los Vaqueros Circle, PO Box 3014, Los Alamitos,
CA 90720-1314, phone +1 714 821 8380; IEEE Computer Society Headquarters, 1730 Massachusetts Ave. NW, Washington, DC 20036-1903; AIP
Circulation and Fulfillment Department, 1NO1, 2 Huntington Quadrangle, Melville, NY 11747-4502. 2007 annual subscription rates: $45 for Computer
Society members (print plus online), $76 (sister society), and $100 (individual nonmember). For AIP society members, 2007 annual subscription rates are
$45 (print plus online). For more information on other subscription prices, see www.computer.org/subscribe/ or https://www.aip.org/forms/journal
_catalog/order_form_fs.html. Computer Society back issues cost $20 for members, $96 for nonmembers; AIP back issues cost $22 for members.
Postmaster: Send undelivered copies and address changes to Computing in Science & Engineering, 445 Hoes Ln., Piscataway, NJ 08855. Periodicals postage
paid at New York, NY, and at additional mailing offices. Canadian GST #125634188. Canada Post Corporation (Canadian distribution) publications mail
agreement number 40013885. Return undeliverable Canadian addresses to PO Box 122, Niagara Falls, ON L2E 6S8 Canada. Printed in the USA.
Copyright & reprint permission: Abstracting is permitted with credit to the source. Libraries are permitted to photocopy beyond the limits of US
copyright law for private use of patrons those articles that carry a code at the bottom of the first page, provided the per-copy fee indicated in the code is
paid through the Copyright Clearance Center, 222 Rosewood Dr., Danvers, MA 01923. For other copying, reprint, or republication permission, write to
Copyright and Permissions Dept., IEEE Publications Administration, 445 Hoes Ln., PO Box 1331, Piscataway, NJ 08855-1331. Copyright © 2007 by the
Institute of Electrical and Electronics Engineers Inc. All rights reserved.
that the Renderer instance has a draw lines method, but The requirement for high-quality 3D graphics and visual-
doesn’t know what kind of output it renders to, be it a Post- ization in Python is mostly solved via the wrapping of VTK;
Script canvas or GTK DrawingArea. Likewise, the renderer MayaVi2, which is part of the Enthought Toolsuite
and canvas don’t know anything about the matplotlib coordi- (http://code.enthought.com), provides a convenient Matlab-
nate system or figure hierarchy or primitive geometry types; like interface to VTK’s fairly complex functionality. Mat-
instead, they rely on the individual artists to do the layout and plotlib provides some rudimentary 3D graphics, and we want
transformation and make the appropriate primitive renderer to improve them so that our users can rely on basic function-
calls. Although this design isn’t always ideal—for example, it ality for surfaces, meshes, and 3D scatterplots without having
doesn’t exploit some of the features in a given output specifi- to depend on the VTK installation. But for anything more so-
cation—it does keep the back ends reasonably simple and phisticated, we prefer to stick to our core competency—high-
dumb, allowing us to quickly add support for a new format. quality interactive scientific 2D graphs—rather than trying to
replicate the already fantastic graphics provided by VTK and
the MayaVi wrappers.
MAY/JUNE 2007 95