Hamsa
Hamsa

Reputation: 483

How to save each figure in a loop using matplotlib

I am trying to save each figure in a for loop in a folder. However for 4-5 runs of the loop only the last figure is saved. Why is it so? What modifications do I need to make?

for t in (0,l[k-1]):
        plt.figure()
        t=resized_right[0:resized_right.shape[0]-1, g+2:g+s+1]
        plt.imshow(resized_right[0:resized_right.shape[0]-1, g+2:g+s+1])
        plt.savefig(dir)
        g+=s-2
        p+=1
        plt.show()

where dir is the directory where the image is to be stored.

Upvotes: 2

Views: 2752

Answers (3)

Alessandro Peca
Alessandro Peca

Reputation: 923

Try to change plt.savefig(dir) with plt.savefig(dir + str(t)). In this way you save t different files in the same directory dir.

Pay also attention to slashes ´/´ in the directory path. Check it by printing dir.

Upvotes: 2

DonFangzahn
DonFangzahn

Reputation: 128

It seems like your saving a figure named dir and overwrite it evertime.

Try adding a variable in plt.savefig(dir). For Example:

 print ("dir" + str(t) + ".png")

Upvotes: 0

Ashok Rayal
Ashok Rayal

Reputation: 405

You have to provide the name of file in savefig and in filename you can append t so 1 image can be saved per loop. Otherwise it will be overridden by next one and you will get only last image

Upvotes: 0

Related Questions