user3601754
user3601754

Reputation: 3872

Python - Loop with figure to save matplotlib

I have a great number of figures i would like to save it for each step of the loop. Actually it s 2 figures as below :

plt.subplots_adjust(hspace=0.5)
plt.subplot(121)
plt.imshow(U2[40,:,:],cmap=cm.hot);plt.colorbar()

plt.subplot(122)
plt.imshow(V2[60,:,:],cmap=cm.hot);plt.colorbar()
plt.show()

My question is how can i save by changing the name at each step as fig1, fig2 as example? Can i use imsave?

Upvotes: 0

Views: 1016

Answers (1)

Ed Smith
Ed Smith

Reputation: 13216

You would replace plt.show() with plt.savefig() and use a format string (to make sure the number is padded with zeros to the same length). This makes life a lot easier when making videos from the png files with ffmpeg (or similar). Also, it is worth adding a tiny pause to ensure the figure is redrawn. For your case, this would look like

plt.subplots_adjust(hspace=0.5)
plt.subplot(121)
plt.imshow(U2[40,:,:],cmap=cm.hot);plt.colorbar()

plt.subplot(122)
plt.imshow(V2[60,:,:],cmap=cm.hot);plt.colorbar()

plt.pause(0.0001)
plt.savefig('./U2V2.{0:07d}.png'.format(step))

Where step is the current step number. You should also consider using a sequential number for each figure (instead of step) which only changes by one each time a figure is generated (again to make video generation easier).

Upvotes: 2

Related Questions