HOWTO · Matplotlib

Differences Between cla(), clf(), and close() Functions in Matplotlib

Compare the Matplotlib pyplot functions cla(), clf(), and close(): cla() clears the current Axes, clf() clears the current Figure, and close() closes a Figure managed by pyplot. Visible-window behavior depends on the backend and execution context.

On this page

Choose the function by the object you want to affect: matplotlib.pyplot.cla() clears the current Axes, matplotlib.pyplot.clf() clears the current Figure, and matplotlib.pyplot.close() closes a Figure. These are pyplot functions, not methods, and each one operates at a different scope. Use cla() to redraw one subplot, clf() to reuse a Figure with a fresh layout, and close() when you are finished with a Figure.

The Difference at a Glance

The three functions form a hierarchy of scope. cla() works on the smallest unit, a single Axes. clf() works on the whole Figure that contains that Axes. close() goes one step further and removes the Figure from pyplot altogether.

Function Acts on Removes What survives
plt.cla() Current Axes Plotted data, labels, title, legend, and other Axes contents The Axes itself, its position in the layout, all sibling Axes, and the Figure
plt.clf() Current Figure Every Axes in the Figure and their contents The Figure object and its window, ready to receive new Axes
plt.close() A Figure managed by pyplot The Figure’s registration in pyplot (and its window in interactive backends) Nothing of that Figure inside pyplot; sibling Figures are unaffected

The scope matters most when a Figure contains several subplots. Clearing an Axes keeps that Axes in the layout, so its position and the other subplots remain available. Clearing a Figure removes all its Axes at once, while leaving the Figure available for new Axes and plots. Closing a Figure ends pyplot’s management of it, which is the only one of the three that frees the Figure’s resources.

All three pyplot functions act on the current Axes or Figure unless you select a target first. If you already hold an Axes or Figure object, the object-level operations ax.clear() and fig.clear() make the target explicit instead of relying on which Axes or Figure happens to be current. For close(), you can pass the Figure directly, as in plt.close(fig).

matplotlib.pyplot.cla()

cla() clears the current Axes’ plotted data, axis labels, title, legend, and other Axes contents. The Axes itself remains in the Figure, in its original position, so a grid of subplots keeps its layout and every neighboring subplot keeps its plot. Clearing an Axes does not remove it from fig.axes and does not change the positions of its neighbors.

This makes cla() the right tool for an update loop: select the Axes, clear its contents, and plot the new data into the same slot. It is the pattern behind simple animations and dashboards that refresh a single panel while the rest of the Figure stays untouched.

The following example builds two subplots, then clears only the second one. The printed checks show that the Figure still contains both Axes, the first Axes still has its line, and the second Axes has no lines and an empty title.

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2 * np.pi, 100)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 3.2))
ax1.plot(x, np.sin(x))
ax1.set_title("Sine (kept)")
ax2.plot(x, np.cos(x), color="orange")
ax2.set_title("Cosine (to be cleared)")
fig.tight_layout()
plt.sca(ax2)
plt.cla()
print(f"axes={len(fig.axes)}; ax1_lines={len(ax1.lines)}; ax2_lines={len(ax2.lines)}; ax2_title={ax2.get_title()!r}")
plt.close(fig)

Output:

axes=2; ax1_lines=1; ax2_lines=0; ax2_title=''

Before the call, both subplots hold a curve:

Two subplots before cla() is called: a sine curve on the left and a cosine curve on the right.

After plt.cla(), the second Axes is empty but still occupies its slot, and the first subplot is unchanged:

The same two subplots after cla(): the sine curve is untouched and the second Axes is empty but still in place.

Choose cla() when the subplot arrangement should stay and only one Axes’ contents should be refreshed. If your code already has the Axes variable, ax.clear() expresses the same Axes-level intent without changing pyplot’s current-Axes selection.

matplotlib.pyplot.clf()

matplotlib.pyplot.clf() clears the current Figure, including all its Axes and their contents. It leaves the Figure object available for reuse and does not close the associated Figure manager, so the same Figure — and, in an interactive session, the same window — can be filled again from scratch. There is no per-Axes clf() operation, because this function works at Figure scope.

After clf(), the Figure has no Axes at all, so you must create new Axes before plotting again; a bare plt.plot() call will implicitly create a fresh Axes for you. If you have several Figures open, select the intended one before calling plt.clf(); fig.clear() is the object-level equivalent and makes the target explicit.

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

fig, axes = plt.subplots(1, 2, figsize=(8, 3.2))
axes[0].plot([0, 1, 2], [0, 1, 4])
axes[0].set_title("Line")
axes[1].bar(["A", "B", "C"], [3, 7, 5])
axes[1].set_title("Bar")
fig.tight_layout()
plt.figure(fig.number)
plt.clf()
print(f"figure_axes={len(fig.axes)}; figure_open={plt.fignum_exists(fig.number)}")
ax = fig.add_subplot(1, 1, 1)
ax.plot([0, 1, 2], [4, 1, 0], color="green")
ax.set_title("Rebuilt on the same Figure")
fig.tight_layout()
plt.close(fig)

Output:

figure_axes=0; figure_open=True

The Figure starts out holding a line plot and a bar chart side by side:

A Figure before clf() is called, holding a line plot and a bar chart in two subplots.

The printout confirms that clf() removed every Axes (figure_axes=0) while the Figure itself stayed open (figure_open=True). The example then adds one new Axes and draws a completely different single plot on the same Figure:

The same Figure after clf() and rebuilding: a single new green line plot fills the whole Figure.

Use clf() when you want to keep a Figure available but rebuild all of its plots or its subplot layout from scratch. Use cla() instead when other Axes in the same Figure must remain untouched.

matplotlib.pyplot.close()

matplotlib.pyplot.close() closes a Figure managed by pyplot. Called with no argument, it closes the current Figure. Pass a Figure object, its number, or a registered Figure name to target a particular Figure, for example plt.close(fig), and pass 'all' to close every Figure at once.

Closing removes the Figure from pyplot’s registry, so plt.fignum_exists() no longer reports it and pyplot no longer keeps its contents in memory. It differs from clearing in an important way: after close(), there is no Figure left to reuse in pyplot, whereas after clf() the same Figure is waiting, empty, for new content. In interactive backends the Figure’s window is destroyed as well, although the exact visible-window behavior depends on the backend and execution context.

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

fig1, ax1 = plt.subplots(figsize=(5, 3.2))
ax1.plot([0, 1, 2], [0, 2, 1])
ax1.set_title("Report 1 (to be closed)")
fig1.tight_layout()
fig2, ax2 = plt.subplots(figsize=(5, 3.2))
ax2.plot([0, 1, 2], [1, 0, 3], color="purple")
ax2.set_title("Report 2 (kept open)")
fig2.tight_layout()
print(f"open_before={plt.get_fignums()}")
plt.close(fig1)
print(f"open_after={plt.get_fignums()}; fig1_open={plt.fignum_exists(fig1.number)}")
plt.close("all")

Output:

open_before=[1, 2]
open_after=[2]; fig1_open=False

Only Figure 2 remains registered after the call, and it is the Figure that stays available for display or saving:

The surviving second Figure after close() removed the first one: a single purple line plot titled Report 2.

Use close() whenever you create Figures you no longer need — above all in scripts and loops that generate many Figures. If you need to reuse the same Figure, clear it with clf() instead; if you need only one subplot refreshed, use cla() or ax.clear().

Memory and the Figure Lifecycle

The three functions also differ in what they cost. cla() and clf() are cheap, repeatable operations: the Figure stays registered with pyplot, its window and buffers stay alive, and only the contents are discarded. That is exactly what you want for a Figure that will be drawn again. close() is the only one that releases the Figure itself, which is why it is the only correct ending for a Figure that will not be drawn again.

Pyplot keeps every Figure it creates registered until it is explicitly closed, and it warns you when that registry grows too large. Creating Figures in a loop without closing them accumulates memory and eventually triggers a RuntimeWarning:

import warnings
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter("always")
    for _ in range(25):
        plt.figure()
    print(f"figures_open={len(plt.get_fignums())}")
    print(f"too_many_figures_warning={any(str(w.message).startswith('More than 20 figures') for w in caught)}")
plt.close("all")
print(f"after_close_all={plt.get_fignums()}")

Output:

figures_open=25
too_many_figures_warning=True
after_close_all=[]

Neither cla() nor clf() would help in that loop, because the problem is the number of registered Figures, not their contents. The rule of thumb is: clear when the same Figure continues, close when it does not. Batch jobs that save one file per Figure should call plt.close(fig) immediately after saving, so peak memory stays flat no matter how many reports the job produces.

Which Function Should You Use?

  • Redrawing one panel of a multi-panel Figure, as in an animation or a live dashboard: use cla() (or ax.clear()), so the layout and the other panels survive.
  • Starting a Figure over with a different layout while keeping the same window or Figure object: use clf() (or fig.clear()), then add fresh Axes.
  • Finished with a Figure, especially inside a loop or a batch script: use close(), passing the Figure, its number, or 'all', so pyplot releases it.

The most common mistakes are using clf() where cla() was meant — which silently wipes every subplot in the Figure, not just the current one — calling cla() while the wrong Axes is current, and expecting a closed Figure to still be reachable through pyplot afterwards. In short: clear one Axes with cla(), clear every Axes in a Figure with clf(), and finish with a Figure using close().