Simple vs. OO API

Matplotlib offers two different APIs, a simple API and an object oriented API. The files mplSimple.py and mplObjects.py, see below, display examples for each of these. Both programs produce the same output, see 9.1.

The code for the simple interface looks easy-to-use: all functions are taken from the pyplot module. No objects are explicitly referenced. The interesting part starts with plt.subplot() which implicitly creates figure and axes objects. Since pyplot keeps track of the current objects, the following calls to xlabel() and ylabel() change the recently created axes object. Since the underlying objects are only treated implicitly, a re-use of these objects is clearly not the purpose of the simple API. This interface has been designed for applications that exit after data are displayed. The disadvantages of the simple API are that the user has less control and that the commands have to be executed in a strict sequence.

#!/usr/bin/env python
#
# file name: mplSimple.py
#
import matplotlib
matplotlib.use( 'TkAgg')
import matplotlib.pyplot as plt
import numpy as np

t = np.arange( 0.0, 1.0, 0.01)
s = np.sin(2*np.pi*t)
c = np.cos(2*np.pi*t)

plt.ion()

plt.subplot( 2, 1, 1)
plt.plot( t, s, 'r')
plt.xlabel( "Phase")
plt.ylabel( "Sin")
plt.subplot( 2, 1, 2)
plt.plot( t, c)
plt.xlabel( "Phase")
plt.ylabel( "Cos")

plt.pause( 3.0)

Ths OO interface is well suited for applications integrating graphics output in some data processing sequence. Data structures can be re-used and the graphics window remains open for many diplay cycles.

#!/usr/bin/env python
#
# file name: mplObjects.py
#
# IPython: from mplObjects import *
#
import matplotlib
matplotlib.use( 'TkAgg')
import matplotlib.pyplot as plt
import numpy as np

plt.ion()

if not plt.get_fignums():
    fig = plt.figure(1, figsize=(11.6,8.2))
else:
    fig = plt.figure(1)
    fig.clear()

sin = fig.add_subplot( 2, 1, 1, ylabel="Sin")
cos = fig.add_subplot( 2, 1, 2, ylabel="Cos")

t = np.arange( 0.0, 1.0, 0.01)
s = np.sin(2*np.pi*t)
c = np.cos(2*np.pi*t)

line_sin, = sin.plot( t, s, 'r')
sin.set_xlabel( "Phase")
line_cos, = cos.plot( t, c)
cos.set_xlabel( "Phase")

fig.canvas.flush_events()
#plt.draw() was in version 1.4.x

Figure 9.1: Sine and cosine
\includegraphics[width=14.76cm]{mpl1.ps}