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:
- the older “pylab” (like Matlab) interface
- the newer one that still imitates the pylab interface but separates NumPy out from it
- the OO interface
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
= [0, 1, 2, 3]
x_vals = [3, 4, 5, 6]
y_vals
pylab.plot(x_vals, y_vals)
'time (s)')
pylab.xlabel('voltage (mV)')
pylab.ylabel('About as simple as it gets, folks')
pylab.title(True)
pylab.grid(#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
= [0, 1, 2, 3]
x_vals = [3, 4, 5, 6]
y_vals
= plt.figure()
fig
= fig.add_subplot(111)
subplot
subplot.plot(x_vals, y_vals)
'time (s)')
plt.xlabel('voltage (mV)')
plt.ylabel('About as simple as it gets, folks')
plt.title(True)
plt.grid(
#plt.savefig('simple_plot') # To save plot as a file.
plt.show()
Notice that the title and labels still belong to plt
. Hm.