How do I tell matplotlib that I am done with a plot?
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
In Matplotlib, the call that actually tells the library you are finished with a figure is plt.close() or plt.close(fig). plt.show() only displays the figure. In simple scripts that may be enough, but in loops, tests, and servers you should close figures explicitly so memory and figure state do not pile up.
Use plt.close(fig) for Explicit Cleanup
The safest habit is to keep a reference to the figure you created and close that exact figure when you are finished.
This pattern works well in scripts, batch jobs, web services, and tests. It makes cleanup explicit instead of depending on backend-specific behavior.
What plt.show() Does and Does Not Do
plt.show() asks Matplotlib to render the current figure or figures. In a desktop script, it usually blocks until the window is closed. That is useful for interactive inspection, but it is not the same as resource cleanup.
Calling plt.close(fig) after plt.show() is a good habit when the script may continue creating more figures afterward.
Close Figures Inside Loops
A common source of memory growth is generating many figures in a loop and never closing them. Each figure remains registered until it is closed.
If you skip the close call in long-running loops, Matplotlib may warn that too many figures are open. More importantly, your process may keep unnecessary memory alive.
Prefer the Object-Oriented API
When code becomes more than a one-off notebook cell, prefer fig, ax = plt.subplots() over relying entirely on the global pyplot state. The object-oriented style makes it easier to know which figure should be saved, shown, or closed.
It also reduces confusion when multiple figures exist at once. Instead of closing “whatever is current,” you close the figure you created.
cla, clf, and close Are Different
Matplotlib provides several cleanup-related calls, but they do different jobs. ax.cla() clears one axes, plt.clf() clears the current figure, and plt.close() removes the figure itself from Matplotlib's registry.
If your goal is to reuse a figure object in a very controlled workflow, clearing may be enough. If your goal is to finish with the figure completely, closing is the correct call.
Notebook and Headless Environments
In Jupyter notebooks, figures are often displayed automatically. Even there, explicit cleanup can help when generating many plots programmatically.
For headless environments such as CI or backend services, use a non-interactive backend and close figures after saving them.
This avoids GUI dependencies and keeps the plotting code suitable for automated runs.
Common Pitfalls
- Assuming
plt.show()automatically handles all cleanup in every environment. - Creating figures in a loop and never closing them.
- Using
plt.close()without tracking which figure you mean when multiple figures are open. - Mixing notebook habits with production code and forgetting explicit resource management.
- Saving a figure after closing it, which can produce empty or invalid output.
Summary
- Use
plt.close(fig)to tell Matplotlib you are finished with a specific figure. - Use
plt.show()for display, not as a substitute for cleanup. - Always close figures in loops, tests, and long-running processes.
- Prefer the object-oriented API so figure ownership is clear.
- In headless environments, save the figure and then close it explicitly.
Related reading
- How do I use np.newaxis?
- How do I use Pandas group-by to get the sum?
- How do I visualize audio data?
- How do recommendation systems work?
- How do I translate an ISO 8601 datetime string into a Python datetime object?
- How do I trim whitespace from a string?
- How do you actually apply a trained model?
- How do you actually apply a trained model?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.