How to use for loop to plot figures saved to different files with matplotlib?
<p>I wanted to plot n independent figures by a for loop, with each figure saved to one file. My code is as following:</p>

<pre><code>import matplotlib.pyplot as plt
import numpy as np
for i in range(len(nfile)): #nfile is a list of file names
    data = np.load(nfile[i])
    plt.plot(data[0], data[1])
    plt.savefig("figure_%d.png"%i, dpi=300)
</code></pre>

<p>I wanted only the plotting of data[i] to show in figure_i.png, but the former plottings (j=0, ..., i-1) also showed in figure_i.png. Is there any way to solve this?</p>

<p>Thanks a lot!</p>

<p>At the beginning of your loop, add:</p>

<pre><code>plt.close()
</code></pre>

python matplotlib plot