Plotting with Matplotlib

Importing Matplotlib

We import the ‘pyplot’ object from Matplotlib, which provides us with an interface for making figures. We usually abbreviate it.

from matplotlib import pyplot as plt

Notebook magics

When we write:

%matplotlib inline

We tell the Jupyter notebook to show figures we generate alongside the code that created it, rather than in a separate window. Lines beginning with a single percent are not python code: they control how the notebook deals with python code.

Lines beginning with two percent signs are “cell magics”, that tell Jupyter notebook how to interpret the particular cell; we’ve seen %%writefile and %%bash for example.

A basic plot

When we write:

from math import sin, cos, pi

myfig = plt.plot([sin(pi * x / 100.0) for x in range(100)])
../_images/03_03_plotting_with_matplotlib_11_0.png

The plot command returns a figure, just like the return value of any function. The notebook then displays this.

To add a title, axis labels etc, we need to get that figure object, and manipulate it. For convenience, matplotlib allows us to do this just by issuing commands to change the “current figure”:

plt.plot([sin(pi * x / 100.0) for x in range(100)])
plt.title("Hello")
Text(0.5, 1.0, 'Hello')
../_images/03_03_plotting_with_matplotlib_14_1.png

But this requires us to keep all our commands together in a single cell, and makes use of a “global” single “current plot”, which, while convenient for quick exploratory sketches, is a bit cumbersome. To produce from our notebook proper plots to use in papers, Python’s plotting library, matplotlib, defines some types we can use to treat individual figures as variables, and manipulate these.

Figures and Axes

We often want multiple graphs in a single figure (e.g. for figures which display a matrix of graphs of different variables for comparison).

So Matplotlib divides a figure object up into axes: each pair of axes is one ‘subplot’. To make a boring figure with just one pair of axes, however, we can just ask for a default new figure, with brand new axes. The relevant function returns a (figure, axis) pair, which we can deal out with parallel assignment.

sine_graph, sine_graph_axes = plt.subplots()
../_images/03_03_plotting_with_matplotlib_19_0.png

Once we have some axes, we can plot a graph on them:

sine_graph_axes.plot([sin(pi * x / 100.0) for x in range(100)], label="sin(x)")
[<matplotlib.lines.Line2D at 0x7ffa44fdd280>]

We can add a title to a pair of axes:

sine_graph_axes.set_title("My graph")
Text(0.5, 1.0, 'My graph')
sine_graph_axes.set_ylabel("f(x)")
Text(3.200000000000003, 0.5, 'f(x)')
sine_graph_axes.set_xlabel("100 x")
Text(0.5, 3.1999999999999993, '100 x')

Now we need to actually display the figure. As always with the notebook, if we make a variable be returned by the last line of a code cell, it gets displayed:

sine_graph
../_images/03_03_plotting_with_matplotlib_27_0.png

We can add another curve:

sine_graph_axes.plot([cos(pi * x / 100.0) for x in range(100)], label="cos(x)")
[<matplotlib.lines.Line2D at 0x7ffa44eac3d0>]
sine_graph
../_images/03_03_plotting_with_matplotlib_30_0.png

A legend will help us distinguish the curves:

sine_graph_axes.legend()
<matplotlib.legend.Legend at 0x7ffa44e97460>
sine_graph
../_images/03_03_plotting_with_matplotlib_33_0.png

Saving figures

We must be able to save figures to disk, in order to use them in papers. This is really easy:

sine_graph.savefig("my_graph.png")

In order to be able to check that it worked, we need to know how to display an arbitrary image in the notebook.

The programmatic way is like this:

from IPython.display import (
    Image,
)  # Get the notebook's own library for manipulating itself.

Image(filename="my_graph.png")
../_images/03_03_plotting_with_matplotlib_39_0.png

Subplots

We might have wanted the \(\sin\) and \(\cos\) graphs on separate axes:

double_graph = plt.figure()
<Figure size 432x288 with 0 Axes>
sin_axes = double_graph.add_subplot(2, 1, 1)  # 2 rows, 1 column, 1st subplot
cos_axes = double_graph.add_subplot(2, 1, 2)
double_graph
../_images/03_03_plotting_with_matplotlib_45_0.png
sin_axes.plot([sin(pi * x / 100.0) for x in range(100)])
[<matplotlib.lines.Line2D at 0x7ffa44df3c10>]
sin_axes.set_ylabel("sin(x)")
Text(3.200000000000003, 0.5, 'sin(x)')
cos_axes.plot([cos(pi * x / 100.0) for x in range(100)])
[<matplotlib.lines.Line2D at 0x7ffa44e3a910>]
cos_axes.set_ylabel("cos(x)")
Text(3.200000000000003, 0.5, 'cos(x)')
cos_axes.set_xlabel("100 x")
Text(0.5, 3.200000000000003, '100 x')
double_graph
../_images/03_03_plotting_with_matplotlib_51_0.png

Versus plots

When we specify a single list to plot, the x-values are just the array index number. We usually want to plot something more meaningful:

double_graph = plt.figure()
sin_axes = double_graph.add_subplot(2, 1, 1)
cos_axes = double_graph.add_subplot(2, 1, 2)
cos_axes.set_ylabel("cos(x)")
sin_axes.set_ylabel("sin(x)")
cos_axes.set_xlabel("x")
Text(0.5, 0, 'x')
../_images/03_03_plotting_with_matplotlib_54_1.png
sin_axes.plot(
    [x / 100.0 for x in range(100)], [sin(pi * x / 100.0) for x in range(100)]
)
cos_axes.plot(
    [x / 100.0 for x in range(100)], [cos(pi * x / 100.0) for x in range(100)]
)
[<matplotlib.lines.Line2D at 0x7ffa44d2e160>]
double_graph
../_images/03_03_plotting_with_matplotlib_56_0.png

Learning More

There’s so much more to learn about matplotlib: pie charts, bar charts, heat maps, 3-d plotting, animated plots, and so on. You can learn all this via the Matplotlib Website. You should try to get comfortable with all this, so please use some time in class, or at home, to work your way through a bunch of the examples.