Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 57 ยท Getting Started

pyplot vs the Object-Oriented API

Understand Matplotlib's two interfaces: the quick pyplot state machine and the explicit fig, ax = plt.subplots() style, and why the second is recommended.

Matplotlib offers two ways to write the same chart. The first, called pyplot style, feels like drawing with a pen: plt.plot(...), plt.title(...), and Matplotlib remembers what you are working on. The second, the object-oriented (OO) style, makes you hold the Figure and Axes in variables and call methods on them. Beginners meet pyplot first, then run into confusing bugs; experts reach for OO. This lesson shows why, and gives you a pattern to use by default.

You have already used both: Your First Plot used plt.plot, while the demos in Anatomy of a Figure used fig, ax = plt.subplots().

The implicit style: pyplot as a state machine

matplotlib.pyplot keeps hidden global state: a current figure and a current Axes. Every plt.something() call acts on those. If none exist, one is created. This is convenient for a one-off line plot.

Python pyplot: the hidden current Axes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

plt.gcf() returns the current Figure and plt.gca() the current Axes. They are how you peek into the hidden state.

The explicit style: fig and ax in your hands

fig, ax = plt.subplots() creates a Figure with one Axes and gives you both. Then you call methods on ax. Note the small naming difference: where pyplot has plt.title, plt.xlabel, plt.xlim, the Axes has ax.set_title, ax.set_xlabel, ax.set_xlim.

Python Object-oriented: the same chart

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The picture is identical. What differs is that nothing here depends on hidden state: each call says exactly which Axes it targets.

Why OO wins as charts grow

With one chart, pyplot is fine. With two or more Axes the implicit style turns confusing, because the "current" Axes changes underneath you. Here is a classic bug:

Python Which plot got the title?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

plt.subplots makes the last Axes created the current one, so the title lands on the right plot, not the left. With OO, you write left.set_title(...) and there is no ambiguity. This single issue is behind countless "my label is on the wrong subplot" questions.

Two styles, one result

pyplot plt.plot, plt.title. Remembers the current Axes.
Object-oriented ax.plot, ax.set_title. You hold the objects.

Both create the same Figure and Axes.

1 / 2

A function that draws on any Axes

The strongest reason for OO is reusable code. A function can accept an ax and draw on it, without caring where it sits.

Python A reusable plotting function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Try writing wave with plt.plot and plt.title and you will see the problem: it can only draw on whichever Axes happens to be current. Libraries like pandas and seaborn follow the OO convention for this reason: they accept ax= so you control where the chart goes (more in Plotting NumPy and pandas Data).

Switching between styles

You can mix them, and sometimes should. plt.subplots, plt.show, plt.savefig, plt.close and plt.style.use are pyplot functions you use even in OO code, because they manage figures and windows. Everything that draws or styles an Axes belongs on ax.

Translating is mechanical:

  • plt.plot becomes ax.plot; plt.bar, plt.hist and plt.scatter likewise.
  • plt.title becomes ax.set_title; plt.xlabel becomes ax.set_xlabel; plt.xlim becomes ax.set_xlim; plt.legend becomes ax.legend.
  • plt.gca() and plt.gcf() hand you the objects when you inherit pyplot-style code.
Python Rescuing implicit code with gca

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Use this skeleton for nearly every chart:

Python
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(6, 4))
ax.plot(x, y)
ax.set_title("What the data shows")
ax.set_xlabel("x name (unit)")
ax.set_ylabel("y name (unit)")
plt.show()

Keep pyplot for creating the figure, showing and saving. Do the drawing and labelling through ax. When you add more panels, change only the first line: fig, axes = plt.subplots(2, 2). See Multiple Subplots.

Do not mix plt.plot(...) calls with explicit Axes in the same figure unless you know which Axes is current. If a line appears in the wrong panel, the implicit style is almost always the cause.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does plt.gca() return?

    gca means get current Axes; gcf means get current Figure. Both read pyplot's hidden state.
  2. 2. In the object-oriented style, which call sets the title of an Axes named ax?

    Axes methods that change settings are named set_*, such as set_title, set_xlabel and set_xlim.
  3. 3. Why does the OO style scale better to figures with several plots?

    pyplot calls act on whichever Axes is current, which can change. Calls on ax always act on that specific Axes.
  4. 4. Which of these is still a pyplot function in OO-style code?

    plt.subplots creates the Figure and Axes, so it remains a pyplot call. Drawing and labelling move to the ax methods.

Summary

  • pyplot style (plt.plot) uses hidden state: the current Figure and Axes, reachable with plt.gcf() and plt.gca().
  • OO style (fig, ax = plt.subplots() then ax.plot) names the target of every call.
  • With several Axes the implicit style can put labels on the wrong plot; OO cannot.
  • Axes setters are named ax.set_title, ax.set_xlabel, ax.set_xlim; plt.subplots, plt.show and plt.savefig stay on pyplot.
  • Functions that take an ax are reusable anywhere; use fig, ax = plt.subplots() as your default skeleton.

Next, control how big the figure is and how it lays out in Figure Size, DPI and Layout.