7 - Matplotlib
Published online by Cambridge University Press: 05 February 2016
Summary
Matplotlib is probably the most popular Python package for plotting data. It can be used through the procedural interface pylab in very quick scripts to produce simple visualizations of data (see Chapter 3) but, as described in this chapter, with care it can also produce high-quality figures for journal articles, books and other publications. Although there is some limited functionality for producing three-dimensional plots (see Section 7.2.3), it is primarily a two-dimensional plotting library.
Matplotlib basics
Matplotlib is a large package organized in a hierarchy: at the highest level is the matplotlib.pyplot module. This provides a “state-machine environment” with a similar interface to MATLAB and allows the user to add plot elements (data points, lines, annotations, etc.) through simple function calls. This is the interface used by pylab, which was introduced in Chapter 3.
At a lower level, which allows more advanced and customizable use, Matplotlib has an object-oriented interface that allows one to create a figure object to which one or more axes objects are attached. Most plotting, annotation and customization then occurs through these axes objects. This is this approach we adopt in this chapter.
To use Matplotlib in this way, we use the following recommended imports:
import matplotlib.pyplot as plt
import numpy as np
Basic figures
Plotting on a single axes object
The top-level object, containing all the elements of a plot is called Figure. To create a figure object, call plt.figure. No arguments are necessary, but optional customization can be specified by setting the values described in Table 7.1. For example,
In [x]: # a default figure, with title “Figure 1”
In [x]: fig = plt.figure()
In [x]: # a small figure with red background
In [x]: fig = plt.figure(’Population density’, figsize=(4.5, 2.),
….: facecolor=’red’)
To actually plot data, we need to create an Axes object – a region of the figure containing the axes, tick-marks, labels, plot lines and markers, and so on. The simplest figure, consisting of a single Axes object, is created and returned with
In [x]: ax = fig.add_subplot(111)
The argument 111 here is a commonly used abbreviation for the tuple (1,1,1) specifying subplot 1 of a figure with 1 row and 1 column of subplots (see Section 7.1.3). The Axes object, ax, is the one on which we can actually plot the data with ax.plot. The essential features of this plot method were described in Chapter 3.
- Type
- Chapter
- Information
- Learning Scientific Programming with Python , pp. 280 - 332Publisher: Cambridge University PressPrint publication year: 2016