Python Notes and Examples

Plotting

A commonly-used package for creating plots is Matplotlib. Matplotlib is built to be able to use NumPy, if you need that.

Note that you can use matplotlib interactively. That is, at the python3 prompt, you can import it and run commands which will pop up a window showing you the plot as you go.

Matplotlib has 3 interfaces:

pylab

This one provides a matlab-like interface, and brings in NumPy with it. It gives you a bunch of simple commands that make plots. Here’s an example:

#!/usr/bin/env python

import pylab

x_vals = [0, 1, 2, 3]
y_vals = [3, 4, 5, 6]
pylab.plot(x_vals, y_vals)

pylab.xlabel('time (s)')
pylab.ylabel('voltage (mV)')
pylab.title('About as simple as it gets, folks')
pylab.grid(True)
#pylab.savefig('simple_plot')  # To save plot as a file.

pylab.show()

This is considered the “old style” and users of matlab will be familiar with it. The pylab import actually brings in NumPy symbols along with the ones for plotting – all under the same “pylab” namespace. Many older matplotlib examples even actually did from pylab import *, but that’s (hopefully) no longer used.

The newer one that imitates the pylab interface

For our simple example above, the imports would look like this:

import matplotlib.pyplot as plt
import numpy as np  # Optional, if you need NumPy.

and the rest of the code would look exactly the same except with “pylab” replaced by “plt”. This separates off the NumPy symbols into their own namespace.

(Note that it’s very common to use NumPy along with matplotlib.)

The OO interface

Same imports as above, but separate out objects such as the main “figure” and the plots (subplots?) it contains:

#!/usr/bin/env python

import matplotlib.pyplot as plt

x_vals = [0, 1, 2, 3]
y_vals = [3, 4, 5, 6]

fig = plt.figure()

subplot = fig.add_subplot(111)
subplot.plot(x_vals, y_vals)

plt.xlabel('time (s)')
plt.ylabel('voltage (mV)')
plt.title('About as simple as it gets, folks')
plt.grid(True)

#plt.savefig('simple_plot')  # To save plot as a file.

plt.show()

Notice that the title and labels still belong to plt. Hm.