Python – Difference between plt.close() and plt.clf()

matplotlibpython

In matplotlib.pyplot, what is the difference between plt.clf() and plt.close()? Will they function the same way?

I am running a loop where at the end of each iteration I am producing a figure and saving the plot. On first couple tries the plot was retaining the old figures in every subsequent plot. I'm looking for, individual plots for each iteration without the old figures, does it matter which one I use? The calculation I'm running takes a very long time and it would be very time consuming to test it out.

Best Answer

plt.close() will close the figure window entirely, where plt.clf() will just clear the figure - you can still paint another plot onto it.

It sounds like, for your needs, you should be preferring plt.clf(), or better yet keep a handle on the line objects themselves (they are returned in lists by plot calls) and use .set_data on those in subsequent iterations.