孙文趋
孙文趋

Reputation: 1406

How to use for loop to plot figures saved to different files with matplotlib?

I wanted to plot n independent figures by a for loop, with each figure saved to one file. My code is as following:

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)

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?

Thanks a lot!

Upvotes: 0

Views: 3604

Answers (1)

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 96339

At the beginning of your loop, add:

plt.close()

Upvotes: 3

Related Questions