matplotlib: Part Two

matplotlib

In the previous article, I introduced matplotlib and some basic pylab statements that can be used to produce graphs. In this article, we’ll use matplotlib and some basic computation to understand experimental data.

numpy Arrays

One of the examples used previously was using pylab to plot a graph of compound interest. matplotlib would be fairly useless, however if it was only used to graph data for such functions, and especially if the plot function only accepted list input. One alternate way of providing input to the plot method is to use numpy.arange():

import random, pylab
import numpy

t = numpy.arange(0,10,.25)
pylab.plot(t,t,'bo')
pylab.show()

In this code fragment, we use numpy.arange, and provide as input three arguments: the minimum, the maximum, and the interval. We supply to plot() three arguments: t, t (again), and ‘bo’ for blue circles. The result is a linear graph where y = x, and the circles appear at intervals of .25.

You can perform some mathematical operations on numpy arrays. For example:

pylab.plot(t,t*2,’bo’)

multiplies the array by a factor of 2, so we get a graph where y = 2*x. We could also square or cube a numpy array, like so:

pylab.plot(t,t*2,’bo’)
pylab.plot(t,t*3,’bo’)

Since having two functions represented by blue dots might be confusing, you probably want to use something else:

pylab.plot(t,t*3,’bs’)

The plot() method can also accept as input the return value of a function. For example, assume that we have a function to return the cosine of a number:

def func(t):
return numpy.cos(2*numpy.pi*t)

Then we can plot the function with pylab:

pylab.figure(1)
pylab.subplot(211)
pylab.plot(t,func(t),’bo’)
pylab.show()

Invoking pylab.figure() is optional because figure(1) will be created by default. The pylab.subplot() method specifies numrows, numcols, and fignum where fignum ranges from 1 to numrows*numcols. The comma in the subplot command are optional if numrows*numcols < 10. Thus, subplot(211) is identical to subplot(2,1,1). If you want to place axes manually (not on a rectangular grid, use the pylab.axes() method, which allows you to specicy a location as axes([left, bottom, with, height]) where all values are in fractional (0 to 1) coordinates.

Another useful method is pylab.savefig, which allows us to save the graph. For example:

pylab.savefig(“cos.png”,dpi=200)

allows us to save the graph as cos.png, with a resolution of 200 dots per inch (dpi). You can also save the graph by clicking on the disk icon on the menu at the top of the graph when the graph displays. Allowed formats include PNG, JPEG, TIFF, SVG and PDF.

External Links:

matplotlib at Wikipedia

The official matplotlib site

Pyplot tutorial at matplotlib.org

Python (x,y) download site