python - 将绘图保存到图像文件,而不是使用Matplotlib显示它
我正在编写一个快速而肮脏的脚本来动态生成绘图。 我使用下面的代码(来自Matplotlib文档)作为起点:
from pylab import figure, axes, pie, title, show
# Make a square figure and axes
figure(1, figsize=(6, 6))
ax = axes([0.1, 0.1, 0.8, 0.8])
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
fracs = [15, 30, 45, 10]
explode = (0, 0.05, 0, 0)
pie(fracs, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True)
title('Raining Hogs and Dogs', bbox={'facecolor': '0.8', 'pad': 5})
show() # Actually, don't show, just save to foo.png
我不想在GUI上显示绘图,相反,我想将绘图保存到文件(例如foo.png),因此,例如,它可以在批处理脚本中使用。 我怎么做?
15个解决方案
988 votes
虽然问题已得到解答,但我想在使用savefig时添加一些有用的提示。 文件格式可以由扩展名指定:
savefig('foo.png')
savefig('foo.pdf')
将分别给出栅格化或矢量化输出,两者都可能有用。 此外,你会发现pylab在图像周围留下了一个慷慨的,通常是不受欢迎的空白空间。 删除它:
savefig('foo.png', bbox_inches='tight')
Hooked answered 2018-12-21T08:03:02Z
139 votes
解决方案是:
pylab.savefig('foo.png')
Lukasz Czerwinski answered 2018-12-21T08:03:22Z
128 votes
正如其他人所说,plt.ion()或fig1.savefig()确实是保存图像的方式。
但是我发现在某些情况下(例如Spyder有plt.ion():交互模式= On),总会显示数字。 我通过强制关闭我的巨型循环中的数字窗口来解决这个问题,所以我在循环期间没有一百万个开放数字:
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 fil