将绘图保存到图像文件而不是使用 Matplotlib 显示它 [英] Save plot to image file instead of displaying it using Matplotlib

查看:39
本文介绍了将绘图保存到图像文件而不是使用 Matplotlib 显示它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个快速而肮脏的脚本来动态生成绘图.我使用下面的代码(来自 Matplotlib 文档)作为起点:

I am writing a quick-and-dirty script to generate plots on the fly. I am using the code below (from Matplotlib documentation) as a starting point:

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)中,例如,它可以在批处理脚本中使用.我该怎么做?

I don't want to display the plot on a GUI, instead, I want to save the plot to a file (say foo.png), so that, for example, it can be used in batch scripts. How do I do that?

推荐答案

虽然问题已经得到解答,但我想在使用 matplotlib.pyplot.savefig.文件格式可以通过扩展名指定:

While the question has been answered, I'd like to add some useful tips when using matplotlib.pyplot.savefig. The file format can be specified by the extension:

from matplotlib import pyplot as plt

plt.savefig('foo.png')
plt.savefig('foo.pdf')

将分别给出光栅化或矢量化的输出,这两种都可能有用.此外,图像周围通常会有不受欢迎的空白,可以通过以下方式删除:

Will give a rasterized or vectorized output respectively, both which could be useful. In addition, there's often an undesirable, whitespace around the image, which can be removed with:

plt.savefig('foo.png', bbox_inches='tight')

注意,如果显示绘图,plt.show() 应该跟在plt.savefig() 之后,否则文件图像将为空白.

Note that if showing the plot, plt.show() should follow plt.savefig(), otherwise the file image will be blank.

这篇关于将绘图保存到图像文件而不是使用 Matplotlib 显示它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆