简体   繁体   English

Python-用图循环以保存matplotlib

[英]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 : 实际上是2位数字,如下所示:

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? 我的问题是如何通过在每个步骤中将名称更改为“ fig1”,“ fig2”作为示例来保存? Can i use imsave? 我可以使用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). 您可以将plt.show()替换为plt.savefig()并使用格式字符串(以确保数字以零填充为相同的长度)。 This makes life a lot easier when making videos from the png files with ffmpeg (or similar). 使用ffmpeg(或类似格式)从png文件制作视频时,这会使生活变得更加轻松。 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. 其中step是当前步骤号。 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). 您还应该考虑为每个图形(而不是步骤)使用一个序号,每次生成图形时该序号只会改变一个(再次使视频生成更容易)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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