tinfangwarble
tinfangwarble

Reputation: 465

savefig loop adds previous plots to figure

I am trying to use a forloop to produce figures for each set of data I have, but while the .show() command produces the correct figure, .savefig() keeps adding the previous plotted values to the new figure. In my forloop, this is the relevant sample of the code.

import matplotlib.pyplot as plt
plt.plot(X,Y[:,0],'o-')
plt.xlabel('x')
plt.savefig('plot'+str(i)+'.png')

As a comparison, here is the savefig plot and here is that shown by show(). As can be seen, the savefig() plot also plotted the previous result.

Upvotes: 33

Views: 29066

Answers (2)

norman
norman

Reputation: 61

I made some beautiful charts before I included plt.clf() to clear the plot each time through the loop. scatterplot1 scatterplot2

In other words, my previous plots were being added to a single figure as shown in the lots above, within my for loop as well. adding [plt.clf()] to clear the plot each time through the loop fixed this problem being clearing the figure before starting the loop iteration at the top to create a new figure with new plots.

TLDR; I included plt.clf() to clear the plot each time through the loop.

Upvotes: 6

Serenity
Serenity

Reputation: 36635

You have to close current figure after saving with function plt.close(): http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.close

Or you have to clean current figure after saving by plt.clf(): http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.clf

Upvotes: 54

Related Questions