Explain Codes LogoExplain Codes Logo

When to use cla(), clf() or close() for clearing a plot

python
plotting
memory-management
interactive-plotting
Anton ShumikhinbyAnton Shumikhin·Sep 12, 2024
TLDR
plt.cla()      # Resets current axis, keeps the figure intact.
plt.clf()      # Clears entire figure, but keeps the window open.
plt.close()    # Closes the figure window, cleaning the memory.

To break it down: Clear the axis with plt.cla(). It is ideal when you want to keep the canvas but change the drawing. Reset the figure with plt.clf(). Choose this when your canvas (aka figure) needs a reset. Close the figure window with plt.close(). It not only removes the plot display but also cleans up the memory.

Example:

# Draw, erase, redraw...kinda like my childhood Etch A Sketch plt.plot(...) # Initial plot plt.cla() # Clear axis but keep the invisible "Etch A Sketch" plt.plot(...) # Draw a new plot on the same axis # Total do-over, new slate for new masterpiece plt.clf() # Clear the whole figure plt.plot(...) # Create a new plot # Show’s over folks! plt.close() # Close the plot window, also cleans memory

Now, let's explore these commands in various case scenarios and understand why they are essential.

Interactive plotting: cla() and clf()

In interactive plotting or IDEs like Jupyter Notebooks, your plot might need frequent updates. plt.cla() clears the axis, and plt.clf() resets the figure, becoming your best allies here. They help redraw plots efficiently, without clogging up your memory.

Memory utilization with close()

Creating multiple figures in a loop? Make sure to call plt.close(fig) after each iteration. It frees up memory resources and avoids those dreaded memory leaks. It's always better to reuse and clear figures than continuously to create new ones.

Save before you clear

If you need to preserve your plot for future reference, use fig.savefig() before you call clf() or close(). It’s the plot’s last selfie before it kicks the bucket.

Smart cleaning strategies

Figure reuse

Reusing figures with fig.clf() or its twin fig.clear() is like doing plot recycling—it's memory-efficient and it's good for your runtime environment. The feeling is akin to having a much-needed plot detox session.

Swift session cleanup

plt.close('all') to the rescue! This one-liner works like a memory Roomba,cleaning all figures after your plotting spree. It's like a data science-friendly version of "leave no trace behind."

Cleaning command selection

Your choice between cla(), clf(), or close() should depend on what's next for your plot. Team cla() for redrawing on the same axis, clf() brings in a fresh canvas, and close() when your plotting is done and it's time to free up some memory.