Matplotlib is a Python package used widely throughout the scientific Python community to produce high quality 2D publication graphics. It transparently supports a wide range of output formats including PNG (and other raster formats), PostScript/EPS, PDF and SVG and has interfaces for all of the major desktop GUI (Graphical User Interface) toolkits.
Matplotlib comes with a convenience sub-package called pyplot
. For consistency with the wider maptlotlib community, this should always be imported as plt
:
import matplotlib.pyplot as plt
At the heart of every matplotlib plot is the "Figure" object. The "Figure" object is the top level concept that can be drawn to one of the many output formats, or simply just to screen. Any object that can be drawn in this way is known as an "Artist" in matplotlib.
Lets create our first artist using pyplot, and then show it:
fig = plt.figure()
plt.show()
<matplotlib.figure.Figure at 0x1047fa810>
On its own, drawing the figure artist is uninteresting and will result in an empty piece of paper (that's why we didn't see anything above).
By far the most useful artist in matplotlib is the "Axes" artist. The Axes artist represents the "data space" of a typical plot. A rectangular axes (the most common axes, but not the only axes, e.g. polar plots) will have two (confusingly named) Axis Artists with tick labels and tick marks.
There is no limit on the number of Axes artists that can exist on a Figure artist. Let's go ahead and create a figure with a single Axes Artist, and show it using pyplot:
ax = plt.axes()
plt.show()
Matplotlib's pyplot
module makes the process of creating graphics easier by allowing us to skip some of the tedious Artist construction. For example, we did not need to manually create the Figure artist with plt.figure
because it was implicit that we needed a figure when we created the Axes artist.
Under the hood matplotlib still had to create a Figure artist; we just didn't need to capture it into a variable. We can access the created object with the "state" functions found in pyplot called gcf
and gca
.
Exercise 1:
pyplot
versions of these functions.As has already been mentioned, most of your time building a graphic in matplotlib will be spent on the Axes artist. Whilst the matplotlib documentation for the Axes artist is very detailed, it is also rather difficult to navigate (though this is an area of ongoing improvement). As a result, it is often easier to find new plot types by looking at the pyplot module's documentation.
The first and most common Axes method is plot
. Go ahead and look at the plot
documentation from the following sources:
Plot can be used to draw one or more lines in axes data space:
ax = plt.axes()
line1, = ax.plot([0, 1, 2, 1.5], [3, 1, 2, 4])
plt.show()
Notice how the axes view limits (ax.viewLim
) have been updated to include the whole of the line.
Should we want to add some spacing around the edges of our axes we could set the axes margin using the Axes artist's margins
method. Alternatively, we could manually set the limits with the Axes artist's set_xlim
and set_ylim
methods.
Exercise 2: Modify the previous example to produce three different figures that control the limits of the axes by:
1. Manually setting the x and y limits to $[0.5, 2]$ and $[1, 5]$ respectively.
2. Defining a margin such that there is 10% whitespace inside the axes around the drawn line (Hint: numbers to margins are normalised such that 0% is 0.0 and 100% is 1.0).
3. Setting a 10% margin on the axes with the lower y limit set to 0. (Note: order is important here)
In truth, the previous example can be simplified to be even shorter. First, we are not using the returned artists, so we could avoid the assignment and just call the appropriate functions. Second, in exactly the same way that we didn't need to manually create a Figure artist when using the pyplot.axes
method, we can remove the plt.axes
if we use the plot
function from pyplot
. Our simple line example then becomes:
plt.plot([0, 1, 2, 1.5], [3, 1, 2, 4])
plt.show()
The simplicity of this example shows how visualisations can be produced quickly and easily with matplotlib, but it is worth remembering that for full control of Figure and Axes artists we can mix the convenience of pyplot
with the power of matplotlib's object oriented design.
Exercise 3: By calling plot
multiple times, create a single axes showing the line plots of $y=sin(x)$ and $y=cos(x)$ in the interval $[0, 2\pi]$ with 200 linearly spaced $x$ samples.
Matplotlib makes it relatively easy to add more than one Axes artist to a figure. The add_subplot
method on a Figure artist, which is wrapped by the subplot
function in pyplot
, adds an Axes artist in the grid position specified. To compute the position, we must tell matplotlib the number of rows and columns to separate the figure into, and which number the axes to be created is (1 based). For example, to create axes at the top right and bottom left of a $3 x 2$ notional grid of Axes artists the grid specifications would be 2, 3, 3
and 2, 3, 4
respectively:
top_right_ax = plt.subplot(2, 3, 3)
bottom_left_ax = plt.subplot(2, 3, 4)
plt.show()
Exercise 3 continued: Copy the answer from the previous task (plotting $y=sin(x)$ and $y=cos(x)$) and add the appropriate plt.subplot
calls to create a figure with two rows of Axes artists, one showing $y=sin(x)$ and the other showing $y=cos(x)$.
Matplotlib comes with a huge variety of different plot types. Here is a quick demonstration of the more common ones.
import numpy as np
x = np.linspace(-180, 180, 60)
y = np.linspace(-90, 90, 30)
x2d, y2d = np.meshgrid(x, y)
data = np.cos(3 * np.deg2rad(x2d)) + np.sin(2 * np.deg2rad(y2d))
plt.contourf(x, y, data)
plt.show()
plt.imshow(data, extent=[-180, 180, -90, 90],
interpolation='nearest', origin='lower')
plt.show()
plt.pcolormesh(x, y, data)
plt.show()
plt.scatter(x2d, y2d, c=data, s=15)
plt.show()
plt.bar(x, data.sum(axis=0), width=np.diff(x)[0])
plt.show()
plt.plot(x, data.sum(axis=0), linestyle='--',
marker='d', markersize=10, color='red')
plt.show()
Matplotlib has convenience functions for the addition of plot elements such as titles, legends, colorbars and text based annotation.
The suptitle
pyplot function allows us to set the title of a figure, and the set_title
method on an Axes artist allows us to set the title of an individual axes. Additionally Axes artists have methods named set_xlabel
and set_ylabel
to label the respective x and y Axis artists (that's Axis, not Axes). Finally, we can add text, located by data coordinates, with the text
method on an Axes artist:
fig = plt.figure()
ax = plt.axes()
# Adjust the created axes so its topmost extent is 0.8 of the figure.
fig.subplots_adjust(top=0.8)
fig.suptitle('Figure title', fontsize=18, fontweight='bold')
ax.set_title('Axes title', fontsize=16)
ax.set_xlabel('The X axis')
ax.set_ylabel('The Y axis $y=f(x)$', fontsize=16)
ax.text(0.5, 0.5, 'Text centered at (0.5, 0.5)\nin data coordinates.',
horizontalalignment='center', fontsize=14)
plt.show()
The creation of a legend is as simple as adding a "label" to lines of interest. This can be done in the call to plt.plot
and then followed up with a call to plt.legend
:
x = np.linspace(-3, 7, 200)
plt.plot(x, 0.5*x**3 - 3*x**2, linewidth=2,
label='$f(x)=0.5x^2-3x^2$')
plt.plot(x, 1.5*x**2 - 6*x, linewidth=2, linestyle='--',
label='Gradient of $f(x)$', )
plt.legend(loc='lower right')
plt.grid()
plt.show()
Colorbars are created with the plt.colorbar
function:
x = np.linspace(-180, 180, 60)
y = np.linspace(-90, 90, 30)
x2d, y2d = np.meshgrid(x, y)
data = np.cos(3 * np.deg2rad(x2d)) + np.sin(2 * np.deg2rad(y2d))
plt.contourf(x, y, data)
plt.colorbar(orientation='horizontal')
plt.show()
Matplotlib comes with powerful annotation capabilities, which are described in detail at http://matplotlib.org/users/annotations_intro.html.
The annotation's power can mean that the syntax is a little harder to read, which is demonstrated by one of the simplest examples of using annotate:
x = np.linspace(-3, 7, 200)
plt.plot(x, 0.5*x**3 - 3*x**2, linewidth=2)
plt.annotate('Local minimum',
xy=(4, -18),
xytext=(-2, -40), fontsize=15,
arrowprops={'facecolor': 'black', 'frac': 0.3})
plt.grid()
plt.show()
Matplotlib allows you to specify a "backend" to drive rendering the figure. The backend includes the graphical user interface (GUI) library to use, and the most used backend (as it is normally the default one) is the "TkAgg" backend. When plt.show()
is called, this backend pops up a figure in a new TkInter window, which is rendered by the anti-grain graphics library (also known as "agg"). Generally, the most common reason to want to change backends is for automated figure production on a headless server. In this situation, the "agg" backend can be used:
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
Note: The backend must be chosen before importing pyplot for the first time, unless the force
keyword is added.
Non-interactive backends such as the "agg" backend will do nothing when plt.show()
is called - this is because there is nowhere (no graphical display) specified for a figure to be displayed.
To save a figure programmatically the savefig
function can be used from any backend:
plt.plot(range(10))
plt.savefig('simple.svg')
For graphical backends, showing and subsequently closing the window of a figure results in the figure being cleared from the matplotlib system. This is not the case for plt.savefig
, which typically should be called before plt.show
.
It is also possible to manually close figures without showing them by using the plt.close
function. This could be called to remove the current figure after saving it with plt.savefig
on the occasion where not clearing the figure might interfere with subsequent plots to be created.