Matplotlib

This notebook is (will be) a small crash course on the functionality of the Matplotlib Python module for creating graphs (and embedding it in notebooks). It is of course no substitute for the proper Matplotlib thorough documentation.

Initialization

We need to add a bit of IPython magic to tell the notebook backend that we want to display all graphs within the notebook. Otherwise they would generate objects instead of displaying into the interface; objects that we later can output to file or display explicitly with plt.show().

This is done by the following declaration:


In [ ]:
%matplotlib inline

Now we need to import the library in our notebook. There are a number of different ways to do it, depending on what part of matplotlib we want to import, and how should it be imported into the namespace. This is one of the most common ones; it means that we will use the plt. prefix to refer to the Matplotlib API


In [ ]:
import matplotlib.pyplot as plt

Matplotlib allows extensive customization of the graph aspect. Some of these customizations come together in "styles". Let's see which styles are available:


In [ ]:
from __future__ import print_function
print(plt.style.available)

In [ ]:
# Let's choose one style. And while we are at it, define thicker lines and big graphic sizes
plt.style.use('bmh')
plt.rcParams['lines.linewidth'] = 1.5
plt.rcParams['figure.figsize'] = (15, 5)

Simple plots

Without much more ado, let's display a simple graphic. For that we define a vector variable, and a function of that vector to be plotted


In [ ]:
import numpy as np
x = np.arange( -10, 11 )
y = x*x

And we plot it


In [ ]:
plt.plot(x,y)
plt.xlabel('x');
plt.ylabel('x square');

We can extensively alter the aspect of the plot. For instance, we can add markers and change color:


In [ ]:
plt.plot(x,y,'ro-');

Matplotlib syntax

Matplotlib commands have two variants:

  • A declarative syntax, with direct plotting commands. It is inspired by Matlab graphics syntax, so if you know Matlab it will be easy. It is the one used above.
  • An object-oriented syntax, more complicated but somehow more powerful

The next cell shows an example of the object-oriented syntax


In [ ]:
# Create a figure object
fig = plt.figure()

# Add a graph to the figure. We get an axes object
ax = fig.add_subplot(1, 1, 1)  # specify (nrows, ncols, axnum)

# Create two vectors: x, y 
x = np.linspace(0, 10, 1000)
y = np.sin(x)

# Plot those vectors on the axes we have
ax.plot(x, y)

# Add another plot to the same axes
y2 = np.cos(x)
ax.plot(x, y2)

# Modify the axes
ax.set_ylim(-1.5, 1.5)

# Add labels
ax.set_xlabel("$x$")
ax.set_ylabel("$f(x)$")
ax.set_title("Sinusoids")

# Add a legend
ax.legend(['sine', 'cosine']);