savefig loop adds previous plots to figure

Question:

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.

Asked By: zalba19

||

Answers:

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

Answered By: Serenity

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.

Answered By: norman
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.