3 - Interlude: simple plotting with pylab
Published online by Cambridge University Press: 05 February 2016
Summary
As Python has grown in popularity, many libraries of packages and modules have become available to extend its functionality in useful ways; Matplotlib is one such library. Matplotlib provides a means of producing graphical plots that can be embedded into applications, displayed on the screen or output as high-quality image files for publication.
Matplotlib has a fully fledged object-oriented interface, which is described in more detail in Chapter 7, but for simple plotting in an interactive shell session, its simpler, procedural pylab interface provides a convenient way of visualizing data. pylab is designed to be easy to learn and functions in a similar way to comparable tools in the commercial MATLAB package.
On a system with Matplotlib installed the pylab package is imported with
>>> import pylab
even though this means prefacing all of the pylab method calls with “pylab.”
Basic plotting
Line plots and scatterplots
The simplest (x, y) line plot is achieved by calling pylab.plot with two iterable objects of the same length (typically lists of numbers or NumPy arrays). For example,
>>> ax = [0., 0.5, 1.0, 1.5, 2.0, 2.5, 3.0]
>>> ay = [0.0, 0.25, 1.0, 2.25, 4.0, 6.25, 9.0]
>>> pylab.plot(ax,ay)
>>> pylab.show()
pylab.plot creates a matplotlib object (here, a Line2D object) and pylab.show() displays it on the screen. Figure 3.1 shows the result; by default the line will be in blue.
To plot (x, y) points as a scatterplot rather than as a line plot, call pylab.scatter instead:
>>> import random
>>> ax, ay = [], []
>>> for i in range(100):
… ax.append(random.random())
… ay.append(random.random())
…
>>> pylab.scatter(ax,ay)
>>> pylab.show()
The resulting plot is shown in Figure 3.2.
We can also save the plot as an image by calling pylab.savefig(filename). The desired image format is deduced from the filename extension. For example,
pylab.savefig(’plot.png’) # save as a PNG image
pylab.savefig(’plot.pdf’) # save as PDF
pylab.savefig(’plot.eps’) # save in Encapsulated PostScript format
Example E3.1 As an example, let's plot the function y = sin2 x for −2π ≤ x ≤ 2π. Using only the Python we've covered in the previous chapter, here is one approach:
We calculate and plot 1,000 (x, y) points, and store them in the lists ax and ay.
- Type
- Chapter
- Information
- Learning Scientific Programming with Python , pp. 84 - 101Publisher: Cambridge University PressPrint publication year: 2016