简体   繁体   中英

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?

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM