matplotlib Getting started with matplotlib Imperative vs. Object-oriented Syntax


Example

Matplotlib supports both object-oriented and imperative syntax for plotting. The imperative syntax is intentionally designed to be very close to Matlab syntax.

The imperative syntax (sometimes called 'state-machine' syntax) issues a string of commands all of which act on the most recent figure or axis (like Matlab). The object-oriented syntax, on the other hand, explicitly acts on the objects (figure, axis, etc.) of interest. A key point in the zen of Python states that explicit is better than implicit so the object-oriented syntax is more pythonic. However, the imperative syntax is convenient for new converts from Matlab and for writing small, "throwaway" plot scripts. Below is an example of the two different styles.

import matplotlib.pyplot as plt
import numpy as np

t = np.arange(0, 2, 0.01)
y = np.sin(4 * np.pi * t)

# Imperative syntax
plt.figure(1)
plt.clf()
plt.plot(t, y)
plt.xlabel('Time (s)')
plt.ylabel('Amplitude (V)')
plt.title('Sine Wave')
plt.grid(True)

# Object oriented syntax
fig = plt.figure(2)
fig.clf()
ax = fig.add_subplot(1,1,1)
ax.plot(t, y)
ax.set_xlabel('Time (s)')
ax.set_ylabel('Amplitude (V)')
ax.set_title('Sine Wave')
ax.grid(True)

Both examples produce the same plot which is shown below.

enter image description here