You've reached the end of your free preview.
Want to read all 3120 pages?
Unformatted text preview: Matplotlib
Release 2.0.0 John Hunter, Darren Dale, Eric Firing, Michael Droettboom and the ma January 16, 2017 CONTENTS I User’s Guide 1 1 Introduction 3 2 Installing 5 3 Tutorials 11 4 Working with text 97 5 Colors 145 6 Customizing matplotlib 173 7 Interactive plots 189 8 Selected Examples 205 9 What’s new in matplotlib 239 10 GitHub Stats 339 11 License 399 12 Credits 403 II 405 The Matplotlib API 13 Plotting commands summary 407 14 API Changes 415 15 The top level matplotlib module 465 16 afm (Adobe Font Metrics interface) 469 17 animation module 473 i 18 artist Module 517 19 Axes class 537 20 axis and tick API 773 21 backends 893 22 cbook 933 23 cm (colormap) 951 24 collections 955 25 colorbar 1125 26 colors 1131 27 dates 1145 28 dviread 1159 29 figure 1163 30 finance 1185 31 font_manager 1197 32 gridspec 1205 33 image 1209 34 legend and legend_handler 1215 35 lines 1223 36 markers 1233 37 mathtext 1237 38 mlab 1257 39 offsetbox 1291 40 patches 1303 41 path 1343 42 patheffects 1351 43 projections 1355 44 pyplot 1363 ii 45 rcsetup 1565 46 sankey 1569 47 scale 1577 48 spines 1587 49 style 1591 50 text 1593 51 ticker 1607 52 tight_layout 1619 53 Working with transformations 1621 54 triangular grids 1643 55 type1font 1655 56 units 1657 57 widgets 1659 III 1675 The Matplotlib FAQ 58 Installation 1677 59 Usage 1685 60 How-To 1697 61 Troubleshooting 1713 62 Environment Variables 1717 63 Working with Matplotlib in Virtual environments 1719 64 Working with Matplotlib on OSX 1721 IV 1725 Matplotlib AxesGrid Toolkit 65 Overview of AxesGrid toolkit 1729 66 The Matplotlib AxesGrid Toolkit User’s Guide 1751 67 The Matplotlib AxesGrid Toolkit API 1767 iii 68 The Matplotlib axes_grid1 Toolkit API 1777 V 1795 mplot3d 69 Matplotlib mplot3d toolkit 1797 VI 1851 Toolkits 70 Mapping Toolkits 1855 71 General Toolkits 1857 72 High-Level Plotting 1861 VII External Resources 1865 73 Books, Chapters and Articles 1867 74 Videos 1869 75 Tutorials 1871 VIII 1873 The Matplotlib Developers’ Guide 76 Contributing 1875 77 Developer’s tips for testing 1883 78 Developer’s tips for documenting matplotlib 1889 79 Developer’s guide for creating scales and transformations 1901 80 Developer’s tips for writing code for Python 2 and 3 1905 81 Working with matplotlib source code 1909 82 Reviewers guideline 1927 83 Release Guide 1929 84 Matplotlib Enhancement Proposals 1935 85 Licenses 1987 86 Default Color changes 1989 iv IX Matplotlib Examples 1993 87 animation Examples 1995 88 api Examples 1999 89 axes_grid Examples 2093 90 color Examples 2145 91 event_handling Examples 2157 92 frontpage Examples 2191 93 images_contours_and_fields Examples 2195 94 lines_bars_and_markers Examples 2211 95 misc Examples 2225 96 mplot3d Examples 2249 97 pie_and_polar_charts Examples 2297 98 pylab_examples Examples 2303 99 pyplots Examples 2747 100scales Examples 2769 101shapes_and_collections Examples 2771 102showcase Examples 2777 103specialty_plots Examples 2795 104statistics Examples 2803 105style_sheets Examples 2835 106subplots_axes_and_figures Examples 2849 107tests Examples 2853 108text_labels_and_annotations Examples 2865 109ticks_and_spines Examples 2871 110units Examples 2885 111user_interfaces Examples 2909 112widgets Examples 2975
v X Glossary 2989 Bibliography 2993 Python Module Index 2995 vi Part I User’s Guide 1 CHAPTER ONE INTRODUCTION Matplotlib is a library for making 2D plots of arrays in Python. Although it has its origins in emulating
the MATLAB®1 graphics commands, it is independent of MATLAB, and can be used in a Pythonic, object
oriented way. Although Matplotlib is written primarily in pure Python, it makes heavy use of NumPy and
other extension code to provide good performance even for large arrays.
Matplotlib is designed with the philosophy that you should be able to create simple plots with just a few
commands, or just one! If you want to see a histogram of your data, you shouldn’t need to instantiate objects,
call methods, set properties, and so on; it should just work.
For years, I used to use MATLAB exclusively for data analysis and visualization. MATLAB excels at making nice looking plots easy. When I began working with EEG data, I found that I needed to write applications
to interact with my data, and developed an EEG analysis application in MATLAB. As the application grew
in complexity, interacting with databases, http servers, manipulating complex data structures, I began to
strain against the limitations of MATLAB as a programming language, and decided to start over in Python.
Python more than makes up for all of MATLAB’s deficiencies as a programming language, but I was having
difficulty finding a 2D plotting package (for 3D VTK more than exceeds all of my needs).
When I went searching for a Python plotting package, I had several requirements:
• Plots should look great - publication quality. One important requirement for me is that the text looks
good (antialiased, etc.)
• Postscript output for inclusion with TeX documents
• Embeddable in a graphical user interface for application development
• Code should be easy enough that I can understand it and extend it
• Making plots should be easy
Finding no package that suited me just right, I did what any self-respecting Python programmer would do:
rolled up my sleeves and dived in. Not having any real experience with computer graphics, I decided to
emulate MATLAB’s plotting capabilities because that is something MATLAB does very well. This had the
added advantage that many people have a lot of MATLAB experience, and thus they can quickly get up to
steam plotting in python. From a developer’s perspective, having a fixed user interface (the pylab interface)
has been very useful, because the guts of the code base can be redesigned without affecting user code.
The Matplotlib code is conceptually divided into three parts: the pylab interface is the set of functions
provided by matplotlib.pylab which allow the user to create plots with code quite similar to MATLAB
1 MATLAB is a registered trademark of The MathWorks, Inc. 3 Matplotlib, Release 2.0.0 figure generating code (Pyplot tutorial). The Matplotlib frontend or Matplotlib API is the set of classes that
do the heavy lifting, creating and managing figures, text, lines, plots and so on (Artist tutorial). This is an
abstract interface that knows nothing about output. The backends are device-dependent drawing devices, aka
renderers, that transform the frontend representation to hardcopy or a display device (What is a backend?).
Example backends: PS creates PostScript® hardcopy, SVG creates Scalable Vector Graphics hardcopy,
Agg creates PNG output using the high quality Anti-Grain Geometry library that ships with Matplotlib,
GTK embeds Matplotlib in a Gtk+ application, GTKAgg uses the Anti-Grain renderer to create a figure and
embed it in a Gtk+ application, and so on for PDF, WxWidgets, Tkinter, etc.
Matplotlib is used by many people in many different contexts. Some people want to automatically generate
PostScript files to send to a printer or publishers. Others deploy Matplotlib on a web application server to
generate PNG output for inclusion in dynamically-generated web pages. Some use Matplotlib interactively
from the Python shell in Tkinter on Windows™. My primary use is to embed Matplotlib in a Gtk+ EEG
application that runs on Windows, Linux and Macintosh OS X. 4 Chapter 1. Introduction CHAPTER TWO INSTALLING There are many different ways to install matplotlib, and the best way depends on what operating system you
are using, what you already have installed, and how you want to use it. To avoid wading through all the
details (and potential complications) on this page, there are several convenient options. 2.1 Installing pre-built packages
2.1.1 Most platforms : scientific Python distributions
The first option is to use one of the pre-packaged python distributions that already provide matplotlib built-in.
The Continuum.io Python distribution (Anaconda or miniconda) and the Enthought distribution (Canopy)
are both excellent choices that “just work” out of the box for Windows, OSX and common Linux platforms.
Both of these distributions include matplotlib and lots of other useful tools. 2.1.2 Linux : using your package manager
If you are on Linux, you might prefer to use your package manager. matplotlib is packaged for almost every
major Linux distribution.
• Debian / Ubuntu : sudo apt-get install python-matplotlib
• Fedora / Redhat : sudo yum install python-matplotlib 2.1.3 Mac OSX : using pip
If you are on Mac OSX you can probably install matplotlib binaries using the standard Python installation
program pip. See Installing OSX binary wheels. 2.1.4 Windows
If you don’t already have Python installed, we recommend using one of the scipy-stack compatible Python
distributions such as WinPython, Python(x,y), Enthought Canopy, or Continuum Anaconda, which have
matplotlib and many of its dependencies, plus other useful packages, preinstalled.
For standard Python installations, install matplotlib using pip:
5 Matplotlib, Release 2.0.0 python -m pip install -U pip setuptools
python -m pip install matplotlib In case Python 2.7 or 3.4 are not installed for all users, the Microsoft Visual C++ 2008 ( 64 bit or 32 bit for
Python 2.7) or Microsoft Visual C++ 2010 ( 64 bit or 32 bit for Python 3.4) redistributable packages need
to be installed.
Matplotlib depends on Pillow for reading and saving JPEG, BMP, and TIFF image files. Matplotlib requires
MiKTeX and GhostScript for rendering text with LaTeX. FFmpeg, avconv, mencoder, or ImageMagick are
required for the animation module.
The following backends should work out of the box: agg, tkagg, ps, pdf and svg. For other backends you
may need to install pycairo, PyQt4, PyQt5, PySide, wxPython, PyGTK, Tornado, or GhostScript.
TkAgg is probably the best backend for interactive use from the standard Python shell or IPython. It is
enabled as the default backend for the official binaries. GTK3 is not supported on Windows.
The Windows wheels (*.whl) on the PyPI download page do not contain test data or example
code. If you want to try the many demos that come in the matplotlib source distribution, download the *.tar.gz file and look in the examples subdirectory. To run the test suite, copy the
lib\matplotlib\tests and lib\mpl_toolkits\tests directories from the source distribution to sys.
prefix\Lib\site-packages\matplotlib and sys.prefix\Lib\site-packages\mpl_toolkits
respectively, and install nose, mock, Pillow, MiKTeX, GhostScript, ffmpeg, avconv, mencoder, ImageMagick, and Inkscape. 2.2 Installing from source
If you are interested in contributing to matplotlib development, running the latest source code, or just like to
build everything yourself, it is not difficult to build matplotlib from source. Grab the latest tar.gz release file
from the PyPI files page, or if you want to develop matplotlib or just need the latest bugfixed version, grab
the latest git version Source install from git.
The standard environment variables CC, CXX, PKG_CONFIG are respected. This means you can set them if
your toolchain is prefixed. This may be used for cross compiling.
export CC=x86_64-pc-linux-gnu-gcc export CXX=x86_64-pc-linux-gnu-g++
PKG_CONFIG=x86_64-pc-linux-gnu-pkg-config export Once you have satisfied the requirements detailed below (mainly python, numpy, libpng and freetype), you
can build matplotlib:
python setup.py build
python setup.py install We provide a setup.cfg file that goes with setup.py which you can use to customize the build process. For
example, which default backend to use, whether some of the optional libraries that matplotlib ships with are
installed, and so on. This file will be particularly useful to those packaging matplotlib.
If you have installed prerequisites to nonstandard places and need to inform matplotlib where they are,
edit setupext.py and add the base dirs to the basedir dictionary entry for your sys.platform. e.g., if
6 Chapter 2. Installing Matplotlib, Release 2.0.0 the header to some required library is in /some/path/include/someheader.h, put /some/path in the
basedir list for your platform. 2.2.1 Build requirements
These are external packages which you will need to install before installing matplotlib. If you are building on
OSX, see Building on OSX. If you are building on Windows, see Building on Windows. If you are installing
dependencies with a package manager on Linux, you may need to install the development packages (look
for a “-dev” postfix) in addition to the libraries themselves.
Required Dependencies python 2.7, 3.4, 3.5 or 3.6 Download python.
numpy 1.7.1 (or later) array support for python (download numpy)
setuptools Setuptools provides extensions for python package installation.
dateutil 1.1 or later Provides extensions to python datetime handling. If using pip, easy_install or installing from source, the installer will attempt to download and install python_dateutil from PyPI.
pyparsing Required for matplotlib’s mathtext math rendering support. If using pip, easy_install or installing from source, the installer will attempt to download and install pyparsing from PyPI.
libpng 1.2 (or later) library for loading and saving PNG files (download). libpng requires zlib.
pytz Used to manipulate time-zone aware datetimes.
FreeType 2.3 or later Library for reading true type font files. If using pip, easy_install or installing from
source, the installer will attempt to locate FreeType in expected locations. If it cannot, try installing
pkg-config, a tool used to find required non-python libraries.
cycler 0.10.0 or later Composable cycle class used for constructing style-cycles
six Required for compatibility between python 2 and python 3
Dependencies for python 2 functools32 Required for compatibility if running on Python 2.7.
subprocess32 Optional, unix only. Backport of the subprocess standard library from 3.2+ for Python 2.7.
It provides better error messages and timeout support.
Optional GUI framework These are optional packages which you may want to install to use matplotlib with a user interface toolkit.
See What is a backend? for more details on the optional matplotlib backends and the capabilities they
provide. 2.2. Installing from source 7 Matplotlib, Release 2.0.0 tk 8.3 or later, not 8.6.0 or 8.6.1 The TCL/Tk widgets library used by the TkAgg backend.
Versions 8.6.0 and 8.6.1 are known to have issues that may result in segfaults when closing multiple
windows in the wrong order.
pyqt 4.4 or later The Qt4 widgets library python wrappers for the Qt4Agg backend
pygtk 2.4 or later The python wrappers for the GTK widgets library for use with the GTK or GTKAgg
wxpython 2.8 or later The python wrappers for the wx widgets library for use with the WX or WXAgg
Optional external programs ffmpeg/avconv or mencoder Required for the animation module to be save out put to movie formats.
ImageMagick Required for the animation module to be able to save to animated gif.
Optional dependencies Pillow If Pillow is installed, matplotlib can read and write a larger selection of image file formats.
pkg-config A tool used to find required non-python libraries. This is not strictly required, but can make
installation go more smoothly if the libraries and headers are not in the expected locations.
Required libraries that ship with matplotlib agg 2.4 The antigrain C++ rendering engine. matplotlib links against the agg template source statically, so
it will not affect anything on your system outside of matplotlib.
qhull 2012.1 A library for computing Delaunay triangulations.
ttconv truetype font utility 2.2.2 Building on Linux
It is easiest to use your system package manager to install the dependencies.
If you are on Debian/Ubuntu, you can get all the dependencies required to build matplotlib with:
sudo apt-get build-dep python-matplotlib If you are on Fedora/RedHat, you can get all the dependencies required to build matplotlib by first installing
yum-builddep and then running:
su -c "yum-builddep python-matplotlib" This does not build matplotlib, but it does get the install the build dependencies, which will make building
from source easier. 8 Chapter 2. Installing Matplotlib, Release 2.0.0 2.2.3 Building on OSX
The build situation on OSX is complicated by the various places one can get the libpng and freetype requirements (darwinports, fink, /usr/X11R6) and the different architectures (e.g., x86, ppc, universal) and
the different OSX version (e.g., 10.4 and 10.5). We recommend that you build the way we do for the OSX
release: get the source from the tarball or the git repository and follow the instruction in README.osx. 2.2.4 Building on Windows
The Python shipped from is compiled with Visual Studio 2008 for versions before
3.3, Visual Studio 2010 for 3.3 and 3.4, and Visual Studio 2015 for 3.5 and 3.6. Python extensions are
recommended to be compiled with the same compiler.
Since there is no canonical Windows package manager, the methods for building freetype, zlib, and libpng
from source code are documented as a build script at matplotlib-winbuild. 2.2. Installing from source 9 Matplotlib, Release 2.0.0 10 Chapter 2. Installing CHAPTER THREE TUTORIALS 3.1 Introductory
3.1.1 Pyplot tutorial
matplotlib.pyplot is a collection of command style functions that make matplotlib work like MATLAB.
Each pyplot function makes some change to a figure: e.g., creates a figure, creates a plotting area in a figure,
plots some lines in a plotting area, decorates the plot with labels, etc. In matplotlib.pyplot various states
are preserved across function calls, so that it keeps track of things like the current figure and plotting area,
and the plotting functions are directed to the current axes (please note that “axes” here and in most places in
the documentation refers to the axes part of a figure and not the strict mathematical term for more than one
import matplotlib.pyplot as plt
plt.show() 11 Matplotlib, Release 2.0.0 4.0 some numbers 3.5
0.0 0.5 1.0 1.5 2.0 2.5 3.0 You may be wondering why the x-axis ranges from 0-3 and the y-axis from 1-4. If you provide a single
list or array to the plot() command, matplotlib assumes it is a sequence of y values, and automatically
generates the x values for you. Since python ranges start with 0, the default x vector has the same length as
y but starts with 0. Hence the x data are [0,1,2,3].
plot() is a versatile command, and will take an arbitrary number of arguments. For example, to plot x
versus y, you can issue the command:
plt.plot([1, 2, 3, 4], [1, 4, 9, 16]) For every x, y pair of arguments, there is an optional third argument which is the format string that indicates
the color and line type of the plot. The letters and symbols of the format string are from MATLAB, and you
concatenate a color string with a line style string. The default format string is ‘b-‘, which is a solid blue line.
For example, to plot the above with red circles, you would issue
import matplotlib.pyplot as plt
plt.plot([1,2,3,4], [1,4,9,16], 'ro')
plt.axis([0, 6, 0, 20])
plt.show() 12 Chapter 3. Tutorials Matplotlib, Release 2.0.0 20.0
0.0 0 1 2 3 4 5 6 See the plot() documentation for a complete list of line styles and format strings. The axis() command
in the example above takes a list of [xmin, xmax, ymin, ymax] and specifies the viewport of the axes.
If matplotlib were limited to working with lists, it would be fairly useless for numeric processing. Generally,
you will use numpy arrays. In fact, all sequences are converted to numpy arrays internally. The example
below illustrates a plotting several lines with different format styles in one command using arrays.
import numpy as np
import matplotlib.pyplot as plt
# evenly sampled time at 200ms intervals
t = np.arange(0., 5., 0.2)
# red dashes, blue squares and green triangles
plt.plot(t, t, 'r--', t, t**2, 'bs',...
View Full Document