Object-Oriented vs pyplot Interface (Matplotlib)

Matplotlib offers two ways to plot: the object-oriented (OO) interface, where you call methods on explicit Figure and Axes objects, and the pyplot interface, where stateful plt functions act on a 'current' figure for you.

Matplotlib

In the pyplot style you write plt.plot(...), plt.title(...), plt.show() and rely on Matplotlib tracking the current figure and axes. It is concise and fine for a single quick chart. In the OO style you write fig, ax = plt.subplots() and then ax.plot(...), ax.set_title(...) — every command names exactly which Axes it affects.

The OO interface is the recommended approach for anything non-trivial, especially figures with multiple subplots, because there is no ambiguity about which plot a command targets and the code is easier to reuse inside functions. The official docs steer new code toward it.

A common best-practice hybrid uses the pyplot helper plt.subplots() to create the objects, then the OO methods for all customization, getting the convenience of pyplot setup with the clarity of explicit objects.

Syntax

ax.plot(x, y)  # OO   vs   plt.plot(x, y)  # pyplot

Examples

Python

import matplotlib.pyplot as plt
# OO style
fig, ax = plt.subplots()
ax.plot([1, 2], [3, 4])
ax.set_title("OO")
print(type(ax).__name__)

Output:

Axes

Learn it in a lesson

See also

Back to the Dictionary