Matplotlib:自动保存imshow()的精确图像
Matplotlib:自动保存imshow()的精确图像
这将在GUI中显示该图形:
import matplotlib.pyplot as plt plt.plot([1, 2, 3], [1, 4, 9]) plt.show()
但是我如何将图形保存到文件中(例如foo.png)?
admin 更改状态以发布 2023年5月23日
正如其他人所说,plt.savefig()
或fig1.savefig()
确实是保存图像的方式。
但是我发现,在某些情况下,图形总是显示出来。(例如,在使用plt.ion()
:交互模式=开启的Spyder中。)我通过强制关闭图形窗口来解决这个问题:
plt.close(figure_object)
(详见文档)。这样,我就不会在大型循环中打开无数个图形。例如使用:
import matplotlib.pyplot as plt fig, ax = plt.subplots( nrows=1, ncols=1 ) # create figure & 1 axis ax.plot([0,1,2], [10,20,3]) fig.savefig('path/to/save/image/to.png') # save the figure to file plt.close(fig) # close the figure window
如果需要,您应该能够稍后重新打开图形,使用fig.show()
(我没有测试过)。
当使用matplotlib.pyplot.savefig
时,可以通过扩展名指定文件格式:\n
from matplotlib import pyplot as plt plt.savefig('foo.png') plt.savefig('foo.pdf')
\n这分别提供了栅格化或矢量化的输出。\n此外,图像周围有时存在不必要的空白,可以通过以下方式删除:\n
plt.savefig('foo.png', bbox_inches='tight')
\n请注意,如果显示图表,则应在plt.savefig()
之后使用plt.show()
;否则,文件图像将为空白。