Section 1: matplotlib
Table of Contents >
Chapter 7 > Section 1
The matplotlib library provides functions that allow you to design
programs that produce publication quality plots. Plots can be
displayed in a window, where they can be manipulated interactively, or
saved directly to a file. We will not attempt to cover the many
different kinds of plots that can be generated but will focus on a
function that produces two-dimensional line plots:
matplotlib.pyplot.plot(*args,
**kwargs)
Plot lines and/or markers to the
Axes
.
args
is a variable length argument, allowing for multiple x, y pairs with an
optional format string. (
http://matplotlib.org/api/pyplot_api.html)
Notice the use of
*args
and
**kwargs
to
specify the parameters, as described in
Chapter
5 Section 2. The (rather lengthy) documentation for this
function must be read carefully if we are to learn more about the
arguments that must be passed when the function is called.
*args
is used to specify, possibly multiple, sets of coordinates for plotting
while
**kwargs
are optional keyword arguments used to
specify properties of the lines to be drawn between data points.
The
matplotlib.pyplot
package contains many other functions
for manipulating plots, including:
and
matplotlib.pyplot.savefig(*args,
**kwargs)
The documentation for this function specifies that it does in fact take
a single required argument in addition to a number of optional keyword
arguments. The required argument is a string that specifies the
path to and name of the file to which the plot is to be
written. The optional keyword arguments allow you to specify
properties such as the resolution, background colour and transparency of
the figure (see
http://matplotlib.org/api/pyplot_api.html
for details).
The following function, for example, consumes a list of times, a list of
positions and the name of a file. It generates a plot of position
against time using a solid green line to connect data points and labels
the axes appropriately. The function then saves the plot to the
specified file.
import matplotlib.pyplot as pyplt
def plot_posn(lot, lop, fname):
"""
(listof Real), (listof Real), str -> NoneType
Effect: generates a plot of positions lop against
times lot and saves plot to file with name fname.
Data points are connected using a solid green line.
"""
pyplt.plot(lot, lop, 'g-')
pyplt.xlabel('Time (s)')
pyplt.ylabel('Position (m)')
pyplt.savefig(fname)
It is recommend that you quickly skim the documentation for the
matplotlib.pyplot
package to learn about the other options available for controlling the
appearance of plots such as drawing tick marks, grid lines and
titles.