Python:将一个或多个图表保存在一个 png 或 pdf 中。
Python:将一个或多个图表保存在一个 png 或 pdf 中。
这将在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()
确实是保存图像的方法。
然而,我发现在某些情况下图形总是显示出来。(例如,使用Spyder的plt.ion()
:交互模式=开启。)我通过用以下方法强制关闭图形窗口来解决这个问题:
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
时,文件格式可以通过扩展名指定:
from matplotlib import pyplot as plt plt.savefig('foo.png') plt.savefig('foo.pdf')
这将分别提供光栅化或矢量化的输出。
此外,有时图片周围会有不希望出现的空白,可以使用以下方法进行删除:
plt.savefig('foo.png', bbox_inches='tight')
请注意,如果要显示图表,则必须在plt.savefig()
之后使用plt.show()
;否则,文件图像将为空白。