0% found this document useful (0 votes)
4 views57 pages

Matplotlib User Guide

The document is a user guide for Matplotlib Release 3.1.1, detailing installation procedures, including installing from official releases, third-party distributions, and building from source. It outlines the necessary dependencies for installation and provides instructions for various operating systems. Additionally, it introduces tutorials for using Matplotlib effectively, covering basic concepts and the structure of figures, axes, and artists.

Uploaded by

chandanhere6
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views57 pages

Matplotlib User Guide

The document is a user guide for Matplotlib Release 3.1.1, detailing installation procedures, including installing from official releases, third-party distributions, and building from source. It outlines the necessary dependencies for installation and provides instructions for various operating systems. Additionally, it introduces tutorials for using Matplotlib effectively, covering basic concepts and the structure of figures, axes, and artists.

Uploaded by

chandanhere6
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Matplotlib

Release 3.1.1

John Hunter, Darren Dale, Eric Firing, Michael Droettboom and the

July 02, 2019


CONTENTS

i
ii
Part I

User’s Guide

1
CHAPTER

ONE

INSTALLING

Note: If you wish to contribute to the project, it’s recommended you install the latest devel-
opment version.

Contents

• Installing
– Installing an official release
∗ Test data
– Third-party distributions of Matplotlib
∗ Scientific Python Distributions
∗ Linux: using your package manager
– Installing from source
∗ Dependencies
∗ Building on Linux
∗ Building on macOS
∗ Building on Windows
· Wheel builds using conda packages
· Conda packages

1.1 Installing an official release

Matplotlib and its dependencies are available as wheel packages for macOS, Windows and
Linux distributions:

python -m pip install -U pip


python -m pip install -U matplotlib

Note: The following backends work out of the box: Agg, ps, pdf, svg and TkAgg.

3
Matplotlib, Release 3.1.1

For support of other GUI frameworks, LaTeX rendering, saving animations and a larger se-
lection of file formats, you may need to install additional dependencies.

Although not required, we suggest also installing IPython for interactive use. To easily install
a complete Scientific Python stack, see Scientific Python Distributions below.

1.1.1 Test data

The 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 *.[Link] file and look in the examples subdirectory.
To run the test suite:
• extract the lib/matplotlib/tests or lib/mpl_toolkits/tests directories from the source
distribution;
• install test dependencies: pytest, Pillow, MiKTeX, GhostScript, ffmpeg, avconv, Im-
ageMagick, and Inkscape;
• run python -mpytest.

1.2 Third-party distributions of Matplotlib

1.2.1 Scientific Python Distributions

Anaconda and Canopy and ActiveState are excellent choices that ”just work” out of the box for
Windows, macOS and common Linux platforms. WinPython is an option for Windows users.
All of these distributions include Matplotlib and lots of other useful (data) science tools.

1.2.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 python3-matplotlib
• Fedora: sudo dnf install python3-matplotlib
• Red Hat: sudo yum install python3-matplotlib
• Arch: sudo pacman -S python-matplotlib

1.3 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 [Link] 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, and see Install from source.

4 Chapter 1. Installing
Matplotlib, Release 3.1.1

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++
export PKG_CONFIG=x86_64-pc-linux-gnu-pkg-config

Once you have satisfied the requirements detailed below (mainly Python, NumPy, libpng and
FreeType), you can build Matplotlib.

cd matplotlib
python -mpip install .

We provide a [Link] file 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 [Link] and add the base dirs to the basedir dictionary entry for your sys.
platform; e.g., if the header of some required library is in /some/path/include/someheader.h,
put /some/path in the basedir list for your platform.

1.3.1 Dependencies

Matplotlib requires the following dependencies:


• Python (>= 3.6)
• FreeType (>= 2.3)
• libpng (>= 1.2)
• NumPy (>= 1.11)
• setuptools
• cycler (>= 0.10.0)
• dateutil (>= 2.1)
• kiwisolver (>= 1.0.0)
• pyparsing
Optionally, you can also install a number of packages to enable better user interface toolk-
its. See What is a backend? for more details on the optional Matplotlib backends and the
capabilities they provide.
• tk (>= 8.3, != 8.6.0 or 8.6.1): for the Tk-based backends;
• PyQt4 (>= 4.6) or PySide (>= 1.0.3): for the Qt4-based backends;
• PyQt5: for the Qt5-based backends;
• PyGObject: for the GTK3-based backends;
• wxpython (>= 4): for the WX-based backends;
• cairocffi (>= 0.8) or pycairo: for the cairo-based backends;
• Tornado: for the WebAgg backend;

1.3. Installing from source 5


Matplotlib, Release 3.1.1

For better support of animation output format and image file formats, LaTeX, etc., you can
install the following:
• ffmpeg/avconv: for saving movies;
• ImageMagick: for saving animated gifs;
• Pillow (>= 3.4): for a larger selection of image file formats: JPEG, BMP, and TIFF image
files;
• LaTeX and GhostScript (>=9.0) : for rendering text with LaTeX.

Note: Matplotlib depends on non-Python libraries.


On Linux and OSX, pkg-config can be used to find required non-Python libraries and thus make
the install go more smoothly if the libraries and headers are not in the expected locations.
If not using pkg-config (in particular on Windows), you may need to set the include path (to the
FreeType, libpng, and zlib headers) and link path (to the FreeType, libpng, and zlib libraries)
explicitly, if they are not in standard locations. This can be done using standard environment
variables – on Linux and OSX:

export CFLAGS='-I/directory/containing/ft2build.h ...'


export LDFLAGS='-L/directory/containing/[Link] ...'

and on Windows:

set CL=/IC:\directory\containing\ft2build.h ...


set LINK=/LIBPATH:C:\directory\containing\[Link] ...

where ... means ”also give, in the same format, the directories containing png.h and zlib.h
for the include path, and for [Link]/[Link] and [Link]/[Link] for the link path.”

Note: The following libraries are shipped with Matplotlib:


• Agg: the Anti-Grain Geometry C++ rendering engine;
• qhull: to compute Delaunay triangulation;
• ttconv: a TrueType font utility.

1.3.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, you can get all the dependencies required to build Matplotlib with:

sudo dnf builddep python-matplotlib

If you are on RedHat, you can get all the dependencies required to build Matplotlib by first
installing yum-builddep and then running:

6 Chapter 1. Installing
Matplotlib, Release 3.1.1

su -c "yum-builddep python-matplotlib"

These commands do not build Matplotlib, but instead get and install the build dependencies,
which will make building from source easier.

1.3.3 Building on macOS

The build situation on macOS is complicated by the various places one can get the libpng
and FreeType requirements (MacPorts, Fink, /usr/X11R6), the different architectures (e.g.,
x86, ppc, universal), and the different macOS versions (e.g., 10.4 and 10.5). We recommend
that you build the way we do for the macOS release: get the source from the tarball or the
git repository and install the required dependencies through a third-party package manager.
Two widely used package managers are Homebrew, and MacPorts. The following example
illustrates how to install libpng and FreeType using brew:

brew install libpng freetype pkg-config

If you are using MacPorts, execute the following instead:

port install libpng freetype pkgconfig

After installing the above requirements, install Matplotlib from source by executing:

python -mpip install .

Note that your environment is somewhat important. Some conda users have found that, to
run the tests, their PYTHONPATH must include /path/to/anaconda/.../site-packages and their
DYLD_FALLBACK_LIBRARY_PATH must include /path/to/anaconda/lib.

1.3.4 Building on Windows

The Python shipped from [Link] is compiled with Visual Stu-


dio 2015 for 3.5+. Python extensions should be compiled with the same com-
piler, see e.g. [Link]
#setting-up-a-build-environment-on-windows for how to set up a build environment.
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.
There are a few possibilities to build Matplotlib on Windows:
• Wheels via matplotlib-winbuild
• Wheels by using conda packages (see below)
• Conda packages (see below)

Wheel builds using conda packages

This is a wheel build, but we use conda packages to get all the requirements. The binary
requirements (png, FreeType,...) are statically linked and therefore not needed during the
wheel install.

1.3. Installing from source 7


Matplotlib, Release 3.1.1

Set up the conda environment. Note, if you want a qt backend, add pyqt to the list of conda
packages.

conda create -n "matplotlib_build" python=3.7 numpy python-dateutil pyparsing tornado␣


,→cycler tk libpng zlib freetype msinttypes

conda activate matplotlib_build

For building, call the script build_alllocal.cmd in the root folder of the repository:

build_alllocal.cmd

Conda packages

The conda packaging scripts for Matplotlib are available at [Link]


matplotlib-feedstock.

8 Chapter 1. Installing
CHAPTER

TWO

TUTORIALS

This page contains more in-depth guides for using Matplotlib. It is broken up into beginner,
intermediate, and advanced sections, as well as sections covering specific topics.
For shorter examples, see our examples page. You can also find external resources and a FAQ
in our user guide.

2.1 Introductory

These tutorials cover the basics of creating visualizations with Matplotlib, as well as some
best-practices in using the package effectively.

Note: Click here to download the full example code

2.1.1 Usage Guide

This tutorial covers some basic usage patterns and best-practices to help you get started with
Matplotlib.

General Concepts

matplotlib has an extensive codebase that can be daunting to many new users. However, most
of matplotlib can be understood with a fairly simple conceptual framework and knowledge of
a few important points.
Plotting requires action on a range of levels, from the most general (e.g., ’contour this 2-D
array’) to the most specific (e.g., ’color this screen pixel red’). The purpose of a plotting
package is to assist you in visualizing your data as easily as possible, with all the necessary
control – that is, by using relatively high-level commands most of the time, and still have the
ability to use the low-level commands when needed.
Therefore, everything in matplotlib is organized in a hierarchy. At the top of the hierarchy
is the matplotlib ”state-machine environment” which is provided by the [Link]
module. At this level, simple functions are used to add plot elements (lines, images, text,
etc.) to the current axes in the current figure.

9
Matplotlib, Release 3.1.1

Note: Pyplot’s state-machine environment behaves similarly to MATLAB and should be most
familiar to users with MATLAB experience.

The next level down in the hierarchy is the first level of the object-oriented interface, in which
pyplot is used only for a few functions such as figure creation, and the user explicitly creates
and keeps track of the figure and axes objects. At this level, the user uses pyplot to create
figures, and through those figures, one or more axes objects can be created. These axes
objects are then used for most plotting actions.
For even more control – which is essential for things like embedding matplotlib plots in GUI
applications – the pyplot level may be dropped completely, leaving a purely object-oriented
approach.

# sphinx_gallery_thumbnail_number = 3
import [Link] as plt
import numpy as np

10 Chapter 2. Tutorials
Matplotlib, Release 3.1.1

Parts of a Figure

Figure

The whole figure. The figure keeps track of all the child Axes, a smattering of ’special’ artists
(titles, figure legends, etc), and the canvas. (Don’t worry too much about the canvas, it is
crucial as it is the object that actually does the drawing to get you your plot, but as the user it
is more-or-less invisible to you). A figure can have any number of Axes, but to be useful should
have at least one.
The easiest way to create a new figure is with pyplot:

2.1. Introductory 11
Matplotlib, Release 3.1.1

fig = [Link]() # an empty figure with no axes


[Link]('No axes on this figure') # Add a title so we know which it is

fig, ax_lst = [Link](2, 2) # a figure with a 2x2 grid of Axes

12 Chapter 2. Tutorials
Matplotlib, Release 3.1.1

Axes

This is what you think of as ’a plot’, it is the region of the image with the data space. A given
figure can contain many Axes, but a given Axes object can only be in one Figure. The Axes
contains two (or three in the case of 3D) Axis objects (be aware of the difference between
Axes and Axis) which take care of the data limits (the data limits can also be controlled via
set via the set_xlim() and set_ylim() Axes methods). Each Axes has a title (set via set_title()),
an x-label (set via set_xlabel()), and a y-label set via set_ylabel()).
The Axes class and it’s member functions are the primary entry point to working with the OO
interface.

Axis

These are the number-line-like objects. They take care of setting the graph limits and gener-
ating the ticks (the marks on the axis) and ticklabels (strings labeling the ticks). The location
of the ticks is determined by a Locator object and the ticklabel strings are formatted by a
Formatter. The combination of the correct Locator and Formatter gives very fine control over
the tick locations and labels.

2.1. Introductory 13
Matplotlib, Release 3.1.1

Artist

Basically everything you can see on the figure is an artist (even the Figure, Axes, and Axis
objects). This includes Text objects, Line2D objects, collection objects, Patch objects ... (you
get the idea). When the figure is rendered, all of the artists are drawn to the canvas. Most
Artists are tied to an Axes; such an Artist cannot be shared by multiple Axes, or moved from
one to another.

Types of inputs to plotting functions

All of plotting functions expect [Link] or [Link].masked_array as input. Classes that are
’array-like’ such as pandas data objects and [Link] may or may not work as intended. It is
best to convert these to [Link] objects prior to plotting.
For example, to convert a [Link]

a = [Link]([Link](4,5), columns = list('abcde'))


a_asarray = [Link]

and to convert a [Link]

b = [Link]([[1,2],[3,4]])
b_asarray = [Link](b)

Matplotlib, pyplot and pylab: how are they related?

Matplotlib is the whole package and [Link] is a module in Matplotlib.


For functions in the pyplot module, there is always a ”current” figure and axes (which is
created automatically on request). For example, in the following example, the first call to
[Link] creates the axes, then subsequent calls to [Link] add additional lines on the same
axes, and [Link], [Link], [Link] and [Link] set the axes labels and title and
add a legend.

x = [Link](0, 2, 100)

[Link](x, x, label='linear')
[Link](x, x**2, label='quadratic')
[Link](x, x**3, label='cubic')

[Link]('x label')
[Link]('y label')

[Link]("Simple Plot")

[Link]()

[Link]()

14 Chapter 2. Tutorials
Matplotlib, Release 3.1.1

pylab is a convenience module that bulk imports [Link] (for plotting) and numpy
(for mathematics and working with arrays) in a single namespace. pylab is deprecated and
its use is strongly discouraged because of namespace pollution. Use pyplot instead.
For non-interactive plotting it is suggested to use pyplot to create the figures and then the
OO interface for plotting.

Coding Styles

When viewing this documentation and examples, you will find different coding styles and
usage patterns. These styles are perfectly valid and have their pros and cons. Just about all
of the examples can be converted into another style and achieve the same results. The only
caveat is to avoid mixing the coding styles for your own code.

Note: Developers for matplotlib have to follow a specific style and guidelines. See The
Matplotlib Developers’ Guide.

Of the different styles, there are two that are officially supported. Therefore, these are the
preferred ways to use matplotlib.
For the pyplot style, the imports at the top of your scripts will typically be:

2.1. Introductory 15
Matplotlib, Release 3.1.1

import [Link] as plt


import numpy as np

Then one calls, for example, [Link], [Link], [Link], plt.figure, [Link], [Link], etc. Use
the pyplot interface for creating figures, and then use the object methods for the rest:

x = [Link](0, 10, 0.2)


y = [Link](x)
fig, ax = [Link]()
[Link](x, y)
[Link]()

So, why all the extra typing instead of the MATLAB-style (which relies on global state and a flat
namespace)? For very simple things like this example, the only advantage is academic: the
wordier styles are more explicit, more clear as to where things come from and what is going
on. For more complicated applications, this explicitness and clarity becomes increasingly
valuable, and the richer and more complete object-oriented interface will likely make the
program easier to write and maintain.
Typically one finds oneself making the same plots over and over again, but with different
data sets, which leads to needing to write specialized functions to do the plotting. The rec-
ommended function signature is something like:

16 Chapter 2. Tutorials
Matplotlib, Release 3.1.1

def my_plotter(ax, data1, data2, param_dict):


"""
A helper function to make a graph

Parameters
----------
ax : Axes
The axes to draw to

data1 : array
The x data

data2 : array
The y data

param_dict : dict
Dictionary of kwargs to pass to [Link]

Returns
-------
out : list
list of artists added
"""
out = [Link](data1, data2, **param_dict)
return out

# which you would then use as:

data1, data2, data3, data4 = [Link](4, 100)


fig, ax = [Link](1, 1)
my_plotter(ax, data1, data2, {'marker': 'x'})

2.1. Introductory 17
Matplotlib, Release 3.1.1

or if you wanted to have 2 sub-plots:

fig, (ax1, ax2) = [Link](1, 2)


my_plotter(ax1, data1, data2, {'marker': 'x'})
my_plotter(ax2, data3, data4, {'marker': 'o'})

18 Chapter 2. Tutorials
Matplotlib, Release 3.1.1

Again, for these simple examples this style seems like overkill, however once the graphs get
slightly more complex it pays off.

Backends

What is a backend?

A lot of documentation on the website and in the mailing lists refers to the ”backend” and
many new users are confused by this term. matplotlib targets many different use cases and
output formats. Some people use matplotlib interactively from the python shell and have
plotting windows pop up when they type commands. Some people run Jupyter notebooks
and draw inline plots for quick data analysis. Others embed matplotlib into graphical user
interfaces like wxpython or pygtk to build rich applications. Some people use matplotlib in
batch scripts to generate postscript images from numerical simulations, and still others run
web application servers to dynamically serve up graphs.
To support all of these use cases, matplotlib can target different outputs, and each of these
capabilities is called a backend; the ”frontend” is the user facing code, i.e., the plotting code,
whereas the ”backend” does all the hard work behind-the-scenes to make the figure. There
are two types of backends: user interface backends (for use in pygtk, wxpython, tkinter, qt4,
or macosx; also referred to as ”interactive backends”) and hardcopy backends to make image
files (PNG, SVG, PDF, PS; also referred to as ”non-interactive backends”).
There are four ways to configure your backend. If they conflict each other, the method men-

2.1. Introductory 19
Matplotlib, Release 3.1.1

tioned last in the following list will be used, e.g. calling use() will override the setting in your
matplotlibrc.
1. The backend parameter in your matplotlibrc file (see Customizing Matplotlib with style
sheets and rcParams):

backend : WXAgg # use wxpython with antigrain (agg) rendering

2. Setting the MPLBACKEND environment variable, either for your current shell or for a single
script. On Unix:

> export MPLBACKEND=module://my_backend


> python simple_plot.py

> MPLBACKEND="module://my_backend" python simple_plot.py

On Windows, only the former is possible:

> set MPLBACKEND=module://my_backend


> python simple_plot.py

Setting this environment variable will override the backend parameter in any
matplotlibrc, even if there is a matplotlibrc in your current working directory. Therefore
setting MPLBACKEND globally, e.g. in your .bashrc or .profile, is discouraged as it might
lead to counter-intuitive behavior.
3. If your script depends on a specific backend you can use the use() function:

import matplotlib
[Link]('PS') # generate postscript output by default

If you use the use() function, this must be done before importing [Link]. Call-
ing use() after pyplot has been imported will have no effect. Using use() will require
changes in your code if users want to use a different backend. Therefore, you should
avoid explicitly calling use() unless absolutely necessary.

Note: Backend name specifications are not case-sensitive; e.g., ’GTK3Agg’ and ’gtk3agg’
are equivalent.

With a typical installation of matplotlib, such as from a binary installer or a linux distribution
package, a good default backend will already be set, allowing both interactive work and plot-
ting from scripts, with output to the screen and/or to a file, so at least initially you will not
need to use any of the methods given above.
If, however, you want to write graphical user interfaces, or a web application server (Mat-
plotlib in a web application server), or need a better understanding of what is going on, read
on. To make things a little more customizable for graphical user interfaces, matplotlib sepa-
rates the concept of the renderer (the thing that actually does the drawing) from the canvas
(the place where the drawing goes). The canonical renderer for user interfaces is Agg which
uses the Anti-Grain Geometry C++ library to make a raster (pixel) image of the figure. All of
the user interfaces except macosx can be used with agg rendering, e.g., WXAgg, GTK3Agg, QT4Agg,
QT5Agg, TkAgg. In addition, some of the user interfaces support other rendering engines. For
example, with GTK+ 3, you can also select Cairo rendering (backend GTK3Cairo).
For the rendering engines, one can also distinguish between vector or raster renderers. Vec-
tor graphics languages issue drawing commands like ”draw a line from this point to this

20 Chapter 2. Tutorials
Matplotlib, Release 3.1.1

point” and hence are scale free, and raster backends generate a pixel representation of the
line whose accuracy depends on a DPI setting.
Here is a summary of the matplotlib renderers (there is an eponymous backend for each;
these are non-interactive backends, capable of writing to a file):

Ren- Filetypes Description


derer
AGG png raster graphics – high quality images using the Anti-Grain Geom-
etry engine
PS ps eps vector graphics – Postscript output
PDF pdf vector graphics – Portable Document Format
SVG svg vector graphics – Scalable Vector Graphics
Cairo png ps pdf raster graphics and vector graphics – using the Cairo graphics li-
svg brary

And here are the user interfaces and renderer combinations supported; these are interactive
backends, capable of displaying to the screen and of using appropriate renderers from the
table above to write to a file:

Back- Description
end
Qt5Agg Agg rendering in a Qt5 canvas (requires PyQt5). This backend can be activated in
IPython with %matplotlib qt5.
ipympl Agg rendering embedded in a Jupyter widget. (requires ipympl). This backend
can be enabled in a Jupyter notebook with %matplotlib ipympl.
GTK3AggAgg rendering to a GTK 3.x canvas (requires PyGObject, and pycairo or cairocffi).
This backend can be activated in IPython with %matplotlib gtk3.
ma- Agg rendering into a Cocoa canvas in OSX. This backend can be activated in
cosx IPython with %matplotlib osx.
Tk- Agg rendering to a Tk canvas (requires TkInter). This backend can be activated
Agg in IPython with %matplotlib tk.
nbAgg Embed an interactive figure in a Jupyter classic notebook. This backend can be
enabled in Jupyter notebooks via %matplotlib notebook.
We- On show() will start a tornado server with an interactive figure.
bAgg
GTK3Cairo
Cairo rendering to a GTK 3.x canvas (requires PyGObject, and pycairo or cairocffi).
Qt4Agg Agg rendering to a Qt4 canvas (requires PyQt4 or pyside). This backend can be
activated in IPython with %matplotlib qt4.
WX- Agg rendering to a wxWidgets canvas (requires wxPython 4). This backend can
Agg be activated in IPython with %matplotlib wx.

ipympl

The Jupyter widget ecosystem is moving too fast to support directly in Matplotlib. To install
ipympl

pip install ipympl


jupyter nbextension enable --py --sys-prefix ipympl

or

2.1. Introductory 21
Matplotlib, Release 3.1.1

conda install ipympl -c conda-forge

See jupyter-matplotlib for more details.

GTK and Cairo

GTK3 backends (both GTK3Agg and GTK3Cairo) depend on Cairo (pycairo>=1.11.0 or cairocffi).

How do I select PyQt4 or PySide?

The QT_API environment variable can be set to either pyqt or pyside to use PyQt4 or PySide,
respectively.
Since the default value for the bindings to be used is PyQt4, matplotlib first tries to import it,
if the import fails, it tries to import PySide.

What is interactive mode?

Use of an interactive backend (see What is a backend?) permits–but does not by itself re-
quire or ensure–plotting to the screen. Whether and when plotting to the screen occurs, and
whether a script or shell session continues after a plot is drawn on the screen, depends on
the functions and methods that are called, and on a state variable that determines whether
matplotlib is in ”interactive mode”. The default Boolean value is set by the matplotlibrc file,
and may be customized like any other configuration parameter (see Customizing Matplotlib
with style sheets and rcParams). It may also be set via [Link](), and its value
may be queried via matplotlib.is_interactive(). Turning interactive mode on and off in the
middle of a stream of plotting commands, whether in a script or in a shell, is rarely needed and
potentially confusing, so in the following we will assume all plotting is done with interactive
mode either on or off.

Note: Major changes related to interactivity, and in particular the role and behavior of
show(), were made in the transition to matplotlib version 1.0, and bugs were fixed in 1.0.1.
Here we describe the version 1.0.1 behavior for the primary interactive backends, with the
partial exception of macosx.

Interactive mode may also be turned on via [Link](), and turned off via
[Link]().

Note: Interactive mode works with suitable backends in ipython and in the ordinary python
shell, but it does not work in the IDLE IDE. If the default backend does not support interac-
tivity, an interactive backend can be explicitly activated using any of the methods discussed
in What is a backend?.

Interactive example

From an ordinary python prompt, or after invoking ipython with no options, try this:

22 Chapter 2. Tutorials
Matplotlib, Release 3.1.1

import [Link] as plt


[Link]()
[Link]([1.6, 2.7])

Assuming you are running version 1.0.1 or higher, and you have an interactive backend in-
stalled and selected by default, you should see a plot, and your terminal prompt should also
be active; you can type additional commands such as:

[Link]("interactive test")
[Link]("index")

and you will see the plot being updated after each line. Since version 1.5, modifying the
plot by other means should also automatically update the display on most backends. Get a
reference to the Axes instance, and call a method of that instance:

ax = [Link]()
[Link]([3.1, 2.2])

If you are using certain backends (like macosx), or an older version of matplotlib, you may not
see the new line added to the plot immediately. In this case, you need to explicitly call draw()
in order to update the plot:

[Link]()

Non-interactive example

Start a fresh session as in the previous example, but now turn interactive mode off:

import [Link] as plt


[Link]()
[Link]([1.6, 2.7])

Nothing happened–or at least nothing has shown up on the screen (unless you are using
macosx backend, which is anomalous). To make the plot appear, you need to do this:

[Link]()

Now you see the plot, but your terminal command line is unresponsive; the show() command
blocks the input of additional commands until you manually kill the plot window.
What good is this–being forced to use a blocking function? Suppose you need a script that
plots the contents of a file to the screen. You want to look at that plot, and then end the script.
Without some blocking command such as show(), the script would flash up the plot and then
end immediately, leaving nothing on the screen.
In addition, non-interactive mode delays all drawing until show() is called; this is more effi-
cient than redrawing the plot each time a line in the script adds a new feature.
Prior to version 1.0, show() generally could not be called more than once in a single script
(although sometimes one could get away with it); for version 1.0.1 and above, this restriction
is lifted, so one can write a script like this:

2.1. Introductory 23
Matplotlib, Release 3.1.1

import numpy as np
import [Link] as plt

[Link]()
for i in range(3):
[Link]([Link](10))
[Link]()

which makes three plots, one at a time. I.e. the second plot will show up, once the first plot
is closed.

Summary

In interactive mode, pyplot functions automatically draw to the screen.


When plotting interactively, if using object method calls in addition to pyplot functions, then
call draw() whenever you want to refresh the plot.
Use non-interactive mode in scripts in which you want to generate one or more figures and
display them before ending or generating a new set of figures. In that case, use show() to
display the figure(s) and to block execution until you have manually destroyed them.

Performance

Whether exploring data in interactive mode or programmatically saving lots of plots, render-
ing performance can be a painful bottleneck in your pipeline. Matplotlib provides a couple
ways to greatly reduce rendering time at the cost of a slight change (to a settable tolerance)
in your plot’s appearance. The methods available to reduce rendering time depend on the
type of plot that is being created.

Line segment simplification

For plots that have line segments (e.g. typical line plots, outlines of polygons, etc.), rendering
performance can be controlled by the [Link] and path.simplify_threshold parameters
in your matplotlibrc file (see Customizing Matplotlib with style sheets and rcParams for more
information about the matplotlibrc file). The [Link] parameter is a boolean indicating
whether or not line segments are simplified at all. The path.simplify_threshold parameter
controls how much line segments are simplified; higher thresholds result in quicker render-
ing.
The following script will first display the data without any simplification, and then display the
same data with simplification. Try interacting with both of them:

import numpy as np
import [Link] as plt
import matplotlib as mpl

# Setup, and create the data to plot


y = [Link](100000)
y[50000:] *= 2
y[[Link](1, np.log10(50000), 400).astype(int)] = -1
(continues on next page)

24 Chapter 2. Tutorials
Matplotlib, Release 3.1.1

(continued from previous page)


[Link]['[Link]'] = True

[Link]['path.simplify_threshold'] = 0.0
[Link](y)
[Link]()

[Link]['path.simplify_threshold'] = 1.0
[Link](y)
[Link]()

Matplotlib currently defaults to a conservative simplification threshold of 1/9. If you want


to change your default settings to use a different value, you can change your matplotlibrc
file. Alternatively, you could create a new style for interactive plotting (with maximal simpli-
fication) and another style for publication quality plotting (with minimal simplification) and
activate them as necessary. See Customizing Matplotlib with style sheets and rcParams for
instructions on how to perform these actions.
The simplification works by iteratively merging line segments into a single vector until the
next line segment’s perpendicular distance to the vector (measured in display-coordinate
space) is greater than the path.simplify_threshold parameter.

Note: Changes related to how line segments are simplified were made in version 2.1. Ren-
dering time will still be improved by these parameters prior to 2.1, but rendering time for
some kinds of data will be vastly improved in versions 2.1 and greater.

Marker simplification

Markers can also be simplified, albeit less robustly than line segments. Marker simplification
is only available to Line2D objects (through the markevery property). Wherever Line2D con-
struction parameter are passed through, such as [Link]() and matplotlib.
[Link](), the markevery parameter can be used:

[Link](x, y, markevery=10)

The markevery argument allows for naive subsampling, or an attempt at evenly spaced (along
the x axis) sampling. See the /gallery/lines_bars_and_markers/markevery_demo for more in-
formation.

Splitting lines into smaller chunks

If you are using the Agg backend (see What is a backend?), then you can make use of the
[Link] rc parameter. This allows you to specify a chunk size, and any lines with
greater than that many vertices will be split into multiple lines, each of which have no more
than [Link] many vertices. (Unless [Link] is zero, in which case there
is no chunking.) For some kind of data, chunking the line up into reasonable sizes can greatly
decrease rendering time.
The following script will first display the data without any chunk size restriction, and then
display the same data with a chunk size of 10,000. The difference can best be seen when the
figures are large, try maximizing the GUI and then interacting with them:

2.1. Introductory 25
Matplotlib, Release 3.1.1

import numpy as np
import [Link] as plt
import matplotlib as mpl
[Link]['path.simplify_threshold'] = 1.0

# Setup, and create the data to plot


y = [Link](100000)
y[50000:] *= 2
y[[Link](1,np.log10(50000), 400).astype(int)] = -1
[Link]['[Link]'] = True

[Link]['[Link]'] = 0
[Link](y)
[Link]()

[Link]['[Link]'] = 10000
[Link](y)
[Link]()

Legends

The default legend behavior for axes attempts to find the location that covers the fewest data
points (loc='best'). This can be a very expensive computation if there are lots of data points.
In this case, you may want to provide a specific location.

Using the fast style

The fast style can be used to automatically set simplification and chunking parameters to
reasonable settings to speed up plotting large amounts of data. It can be used simply by
running:

import [Link] as mplstyle


[Link]('fast')

It is very light weight, so it plays nicely with other styles, just make sure the fast style is
applied last so that other styles do not overwrite the settings:

[Link](['dark_background', 'ggplot', 'fast'])

Note: Click here to download the full example code

2.1.2 Pyplot tutorial

An introduction to the pyplot interface.

26 Chapter 2. Tutorials
Matplotlib, Release 3.1.1

Intro to pyplot

[Link] 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 [Link] 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 axis).

Note: the pyplot API is generally less-flexible than the object-oriented API. Most of the
function calls you see here can also be called as methods from an Axes object. We recommend
browsing the tutorials and examples to see how this works.

Generating visualizations with pyplot is very quick:

import [Link] as plt


[Link]([1, 2, 3, 4])
[Link]('some numbers')
[Link]()

You may be wondering why the x-axis ranges from 0-3 and the y-axis from 1-4. If you provide a

2.1. Introductory 27
Matplotlib, Release 3.1.1

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:

[Link]([1, 2, 3, 4], [1, 4, 9, 16])

Formatting the style of your plot

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

[Link]([1, 2, 3, 4], [1, 4, 9, 16], 'ro')


[Link]([0, 6, 0, 20])
[Link]()

28 Chapter 2. Tutorials
Matplotlib, Release 3.1.1

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 view-
port of the axes.
If matplotlib were limited to working with lists, it would be fairly useless for numeric pro-
cessing. 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

# evenly sampled time at 200ms intervals


t = [Link](0., 5., 0.2)

# red dashes, blue squares and green triangles


[Link](t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
[Link]()

2.1. Introductory 29
Matplotlib, Release 3.1.1

Plotting with keyword strings

There are some instances where you have data in a format that lets you access particular
variables with strings. For example, with [Link] or [Link].
Matplotlib allows you provide such an object with the data keyword argument. If provided,
then you may generate plots with the strings corresponding to these variables.

data = {'a': [Link](50),


'c': [Link](0, 50, 50),
'd': [Link](50)}
data['b'] = data['a'] + 10 * [Link](50)
data['d'] = [Link](data['d']) * 100

[Link]('a', 'b', c='c', s='d', data=data)


[Link]('entry a')
[Link]('entry b')
[Link]()

30 Chapter 2. Tutorials
Matplotlib, Release 3.1.1

Plotting with categorical variables

It is also possible to create a plot using categorical variables. Matplotlib allows you to pass
categorical variables directly to many plotting functions. For example:

names = ['group_a', 'group_b', 'group_c']


values = [1, 10, 100]

[Link](figsize=(9, 3))

[Link](131)
[Link](names, values)
[Link](132)
[Link](names, values)
[Link](133)
[Link](names, values)
[Link]('Categorical Plotting')
[Link]()

2.1. Introductory 31
Matplotlib, Release 3.1.1

Controlling line properties

Lines have many attributes that you can set: linewidth, dash style, antialiased, etc; see
[Link].Line2D. There are several ways to set line properties
• Use keyword args:

[Link](x, y, linewidth=2.0)

• Use the setter methods of a Line2D instance. plot returns a list of Line2D objects; e.g.,
line1, line2 = plot(x1, y1, x2, y2). In the code below we will suppose that we have
only one line so that the list returned is of length 1. We use tuple unpacking with line,
to get the first element of that list:

line, = [Link](x, y, '-')


line.set_antialiased(False) # turn off antialiasing

• Use the setp() command. The example below uses a MATLAB-style command to set mul-
tiple properties on a list of lines. setp works transparently with a list of objects or a sin-
gle object. You can either use python keyword arguments or MATLAB-style string/value
pairs:

lines = [Link](x1, y1, x2, y2)


# use keyword args
[Link](lines, color='r', linewidth=2.0)
# or MATLAB style string value pairs
[Link](lines, 'color', 'r', 'linewidth', 2.0)

Here are the available Line2D properties.

Property Value Type


alpha float
animated [True | False]
antialiased or aa [True | False]
clip_box a [Link] instance
clip_on [True | False]
clip_path a Path instance and a Transform instance, a Patch
color or c any matplotlib color
Continued on next page

32 Chapter 2. Tutorials
Matplotlib, Release 3.1.1

Table 1 – continued from previous page


Property Value Type
contains the hit testing function
dash_capstyle ['butt' | 'round' | 'projecting']
dash_joinstyle ['miter' | 'round' | 'bevel']
dashes sequence of on/off ink in points
data ([Link] xdata, [Link] ydata)
figure a matplotlib.fi[Link] instance
label any string
linestyle or ls [ '-' | '--' | '-.' | ':' | 'steps' | ...]
linewidth or lw float value in points
marker [ '+' | ',' | '.' | '1' | '2' | '3' | '4' ]
markeredgecolor or mec any matplotlib color
markeredgewidth or mew float value in points
markerfacecolor or mfc any matplotlib color
markersize or ms float
markevery [ None | integer | (startind, stride) ]
picker used in interactive line selection
pickradius the line pick selection radius
solid_capstyle ['butt' | 'round' | 'projecting']
solid_joinstyle ['miter' | 'round' | 'bevel']
transform a [Link] instance
visible [True | False]
xdata [Link]
ydata [Link]
zorder any number

To get a list of settable line properties, call the setp() function with a line or lines as argument

In [69]: lines = [Link]([1, 2, 3])

In [70]: [Link](lines)
alpha: float
animated: [True | False]
antialiased or aa: [True | False]
...snip

Working with multiple figures and axes

MATLAB, and pyplot, have the concept of the current figure and the current axes. All plot-
ting commands apply to the current axes. The function gca() returns the current axes (a
[Link] instance), and gcf() returns the current figure ([Link]
instance). Normally, you don’t have to worry about this, because it is all taken care of behind
the scenes. Below is a script to create two subplots.

def f(t):
return [Link](-t) * [Link](2*[Link]*t)

t1 = [Link](0.0, 5.0, 0.1)


t2 = [Link](0.0, 5.0, 0.02)

(continues on next page)

2.1. Introductory 33
Matplotlib, Release 3.1.1

(continued from previous page)


[Link]()
[Link](211)
[Link](t1, f(t1), 'bo', t2, f(t2), 'k')

[Link](212)
[Link](t2, [Link](2*[Link]*t2), 'r--')
[Link]()

The figure() command here is optional because figure(1) will be created by default, just
as a subplot(111) will be created by default if you don’t manually specify any axes. The
subplot() command specifies numrows, numcols, plot_number where plot_number ranges from
1 to numrows*numcols. The commas in the subplot command are optional if numrows*numcols<10.
So subplot(211) is identical to subplot(2, 1, 1).
You can create an arbitrary number of subplots and axes. If you want to place an axes man-
ually, i.e., not on a rectangular grid, use the axes() command, which allows you to specify
the location as axes([left, bottom, width, height]) where all values are in fractional (0 to
1) coordinates. See /gallery/subplots_axes_and_figures/axes_demo for an example of placing
axes manually and /gallery/subplots_axes_and_figures/subplot_demo for an example with lots
of subplots.
You can create multiple figures by using multiple figure() calls with an increasing figure
number. Of course, each figure can contain as many axes and subplots as your heart desires:

34 Chapter 2. Tutorials
Matplotlib, Release 3.1.1

import [Link] as plt


[Link](1) # the first figure
[Link](211) # the first subplot in the first figure
[Link]([1, 2, 3])
[Link](212) # the second subplot in the first figure
[Link]([4, 5, 6])

[Link](2) # a second figure


[Link]([4, 5, 6]) # creates a subplot(111) by default

[Link](1) # figure 1 current; subplot(212) still current


[Link](211) # make subplot(211) in figure1 current
[Link]('Easy as 1, 2, 3') # subplot 211 title

You can clear the current figure with clf() and the current axes with cla(). If you find it
annoying that states (specifically the current image, figure and axes) are being maintained
for you behind the scenes, don’t despair: this is just a thin stateful wrapper around an object
oriented API, which you can use instead (see Artist tutorial)
If you are making lots of figures, you need to be aware of one more thing: the memory required
for a figure is not completely released until the figure is explicitly closed with close(). Deleting
all references to the figure, and/or using the window manager to kill the window in which the
figure appears on the screen, is not enough, because pyplot maintains internal references
until close() is called.

Working with text

The text() command can be used to add text in an arbitrary location, and the xlabel(),
ylabel() and title() are used to add text in the indicated locations (see Text in Matplotlib
Plots for a more detailed example)

mu, sigma = 100, 15


x = mu + sigma * [Link](10000)

# the histogram of the data


n, bins, patches = [Link](x, 50, density=1, facecolor='g', alpha=0.75)

[Link]('Smarts')
[Link]('Probability')
[Link]('Histogram of IQ')
[Link](60, .025, r'$\mu=100,\ \sigma=15$')
[Link]([40, 160, 0, 0.03])
[Link](True)
[Link]()

2.1. Introductory 35
Matplotlib, Release 3.1.1

All of the text() commands return an [Link] instance. Just as with with lines
above, you can customize the properties by passing keyword arguments into the text functions
or using setp():

t = [Link]('my data', fontsize=14, color='red')

These properties are covered in more detail in Text properties and layout.

Using mathematical expressions in text

matplotlib accepts TeX equation expressions in any text expression. For example to write the
expression σi = 15 in the title, you can write a TeX expression surrounded by dollar signs:

[Link](r'$\sigma_i=15$')

The r preceding the title string is important – it signifies that the string is a raw string and not
to treat backslashes as python escapes. matplotlib has a built-in TeX expression parser and
layout engine, and ships its own math fonts – for details see Writing mathematical expressions.
Thus you can use mathematical text across platforms without requiring a TeX installation.
For those who have LaTeX and dvipng installed, you can also use LaTeX to format your text
and incorporate the output directly into your display figures or saved postscript – see Text
rendering With LaTeX.

36 Chapter 2. Tutorials
Matplotlib, Release 3.1.1

Annotating text

The uses of the basic text() command above place text at an arbitrary position on the Axes.
A common use for text is to annotate some feature of the plot, and the annotate() method
provides helper functionality to make annotations easy. In an annotation, there are two points
to consider: the location being annotated represented by the argument xy and the location of
the text xytext. Both of these arguments are (x,y) tuples.

ax = [Link](111)

t = [Link](0.0, 5.0, 0.01)


s = [Link](2*[Link]*t)
line, = [Link](t, s, lw=2)

[Link]('local max', xy=(2, 1), xytext=(3, 1.5),


arrowprops=dict(facecolor='black', shrink=0.05),
)

[Link](-2, 2)
[Link]()

In this basic example, both the xy (arrow tip) and xytext locations (text location) are in
data coordinates. There are a variety of other coordinate systems one can choose – see
Basic annotation and Advanced Annotation for details. More examples can be found in

2.1. Introductory 37
Matplotlib, Release 3.1.1

/gallery/text_labels_and_annotations/annotation_demo.

Logarithmic and other nonlinear axes

[Link] supports not only linear axis scales, but also logarithmic and logit scales.
This is commonly used if data spans many orders of magnitude. Changing the scale of an axis
is easy:
[Link](’log’)
An example of four plots with the same data and different scales for the y axis is shown below.

from [Link] import NullFormatter # useful for `logit` scale

# Fixing random state for reproducibility


[Link](19680801)

# make up some data in the interval ]0, 1[


y = [Link](loc=0.5, scale=0.4, size=1000)
y = y[(y > 0) & (y < 1)]
[Link]()
x = [Link](len(y))

# plot with various axes scales


[Link]()

# linear
[Link](221)
[Link](x, y)
[Link]('linear')
[Link]('linear')
[Link](True)

# log
[Link](222)
[Link](x, y)
[Link]('log')
[Link]('log')
[Link](True)

# symmetric log
[Link](223)
[Link](x, y - [Link]())
[Link]('symlog', linthreshy=0.01)
[Link]('symlog')
[Link](True)

# logit
[Link](224)
[Link](x, y)
[Link]('logit')
(continues on next page)

38 Chapter 2. Tutorials
Matplotlib, Release 3.1.1

(continued from previous page)


[Link]('logit')
[Link](True)
# Format the minor tick labels of the y-axis into empty strings with
# `NullFormatter`, to avoid cumbering the axis with too many labels.
[Link]().yaxis.set_minor_formatter(NullFormatter())
# Adjust the subplot layout, because the logit one may take more space
# than usual, due to y-tick labels like "1 - 10^{-3}"
plt.subplots_adjust(top=0.92, bottom=0.08, left=0.10, right=0.95, hspace=0.25,
wspace=0.35)

[Link]()

It is also possible to add your own scale, see Developer’s guide for creating scales and trans-
formations for details.

Note: Click here to download the full example code

2.1.3 Sample plots in Matplotlib

Here you’ll find a host of example plots with the code that generated them.

2.1. Introductory 39
Matplotlib, Release 3.1.1

Line Plot

Here’s how to create a line plot with text labels using plot().

Fig. 1: Simple Plot

Multiple subplots in one figure

Multiple axes (i.e. subplots) are created with the subplot() function:

Fig. 2: Subplot

Images

Matplotlib can display images (assuming equally spaced horizontal dimensions) using the
imshow() function.

40 Chapter 2. Tutorials
Matplotlib, Release 3.1.1

Fig. 3: Example of using imshow() to display a CT scan

Contouring and pseudocolor

The pcolormesh() function can make a colored representation of a two-dimensional array, even
if the horizontal dimensions are unevenly spaced. The contour() function is another way to
represent the same data:

Fig. 4: Example comparing pcolormesh() and contour() for plotting two-dimensional data

Histograms

The hist() function automatically generates histograms and returns the bin counts or proba-
bilities:

Paths

You can add arbitrary paths in Matplotlib using the [Link] module:

2.1. Introductory 41
Matplotlib, Release 3.1.1

Fig. 5: Histogram Features

Fig. 6: Path Patch

42 Chapter 2. Tutorials
Matplotlib, Release 3.1.1

Three-dimensional plotting

The mplot3d toolkit (see Getting started and mplot3d-examples-index) has support for simple
3d graphs including surface, wireframe, scatter, and bar charts.

Fig. 7: Surface3d

Thanks to John Porter, Jonathon Taylor, Reinier Heeres, and Ben Root for the mplot3d toolkit.
This toolkit is included with all standard Matplotlib installs.

Streamplot

The streamplot() function plots the streamlines of a vector field. In addition to simply plotting
the streamlines, it allows you to map the colors and/or line widths of streamlines to a separate
parameter, such as the speed or local intensity of the vector field.
This feature complements the quiver() function for plotting vector fields. Thanks to Tom
Flannaghan and Tony Yu for adding the streamplot function.

Ellipses

In support of the Phoenix mission to Mars (which used Matplotlib to display ground tracking
of spacecraft), Michael Droettboom built on work by Charlie Moad to provide an extremely
accurate 8-spline approximation to elliptical arcs (see Arc), which are insensitive to zoom
level.

Bar charts

Use the bar() function to make bar charts, which includes customizations such as error bars:
You can also create stacked bars (bar_stacked.py), or horizontal bar charts ([Link]).

Pie charts

The pie() function allows you to create pie charts. Optional features include auto-labeling the
percentage of area, exploding one or more wedges from the center of the pie, and a shadow

2.1. Introductory 43
Matplotlib, Release 3.1.1

Fig. 8: Streamplot with various plotting options.

Fig. 9: Ellipse Demo

44 Chapter 2. Tutorials
Matplotlib, Release 3.1.1

Fig. 10: Barchart Demo

effect. Take a close look at the attached code, which generates this figure in just a few lines
of code.

Fig. 11: Pie Features

Tables

The table() function adds a text table to an axes.

2.1. Introductory 45
Matplotlib, Release 3.1.1

Fig. 12: Table Demo

Scatter plots

The scatter() function makes a scatter plot with (optional) size and color arguments. This
example plots changes in Google’s stock price, with marker sizes reflecting the trading volume
and colors varying with time. Here, the alpha attribute is used to make semitransparent circle
markers.

Fig. 13: Scatter Demo2

GUI widgets

Matplotlib has basic GUI widgets that are independent of the graphical user interface you
are using, allowing you to write cross GUI figures and widgets. See [Link] and
the widget examples.

Filled curves

The fill() function lets you plot filled curves and polygons:

46 Chapter 2. Tutorials
Matplotlib, Release 3.1.1

Fig. 14: Slider and radio-button GUI.

Fig. 15: Fill

2.1. Introductory 47
Matplotlib, Release 3.1.1

Thanks to Andrew Straw for adding this function.

Date handling

You can plot timeseries data with major and minor ticks and custom tick formatters for both.

Fig. 16: Date

See [Link] and [Link] for details and usage.

Log plots

The semilogx(), semilogy() and loglog() functions simplify the creation of logarithmic plots.

Fig. 17: Log Demo

Thanks to Andrew Straw, Darren Dale and Gregory Lielens for contributions log-scaling in-
frastructure.

48 Chapter 2. Tutorials
Matplotlib, Release 3.1.1

Polar plots

The polar() function generates polar plots.

Fig. 18: Polar Demo

Legends

The legend() function automatically generates figure legends, with MATLAB-compatible


legend-placement functions.

Fig. 19: Legend

Thanks to Charles Twardy for input on the legend function.

TeX-notation for text objects

Below is a sampling of the many TeX expressions now supported by Matplotlib’s internal
mathtext engine. The mathtext module provides TeX style mathematical expressions using
FreeType and the DejaVu, BaKoMa computer modern, or STIX fonts. See the matplotlib.
mathtext module for additional details.

2.1. Introductory 49
Matplotlib, Release 3.1.1

Fig. 20: Mathtext Examples

Matplotlib’s mathtext infrastructure is an independent implementation and does not require


TeX or any external packages installed on your computer. See the tutorial at Writing mathe-
matical expressions.

Native TeX rendering

Although Matplotlib’s internal math rendering engine is quite powerful, sometimes you need
TeX. Matplotlib supports external TeX rendering of strings with the usetex option.

Fig. 21: Tex Demo

50 Chapter 2. Tutorials
Matplotlib, Release 3.1.1

EEG GUI

You can embed Matplotlib into pygtk, wx, Tk, or Qt applications. Here is a screenshot of an
EEG viewer called pbrain.

The lower axes uses specgram() to plot the spectrogram of one of the EEG channels.
For examples of how to embed Matplotlib in different toolkits, see:
• /gallery/user_interfaces/embedding_in_gtk3_sgskip
• /gallery/user_interfaces/embedding_in_wx2_sgskip
• /gallery/user_interfaces/mpl_with_glade3_sgskip
• /gallery/user_interfaces/embedding_in_qt_sgskip
• /gallery/user_interfaces/embedding_in_tk_sgskip

2.1. Introductory 51
Matplotlib, Release 3.1.1

XKCD-style sketch plots

Just for fun, Matplotlib supports plotting in the style of xkcd.

Fig. 22: xkcd

Subplot example

Many plot types can be combined in one figure to create powerful and flexible representations
of data.

52 Chapter 2. Tutorials
Matplotlib, Release 3.1.1

import [Link] as plt


import numpy as np

[Link](19680801)
data = [Link](2, 100)

fig, axs = [Link](2, 2, figsize=(5, 5))


axs[0, 0].hist(data[0])
axs[1, 0].scatter(data[0], data[1])
axs[0, 1].plot(data[0], data[1])
axs[1, 1].hist2d(data[0], data[1])

[Link]()

Note: Click here to download the full example code

2.1.4 Image tutorial

A short tutorial on plotting images with Matplotlib.

2.1. Introductory 53

You might also like