Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
370 views
in Technique[技术] by (71.8m points)

python - 将绘图保存到图像文件,而不是使用Matplotlib显示(Save plot to image file instead of displaying it using 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:

(我使用下面的代码(来自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

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.

(我不想将图形显示在GUI上,而是要将图形保存到文件(例如foo.png)中,以便可以在批处理脚本中使用它。)

How do I do that?

(我怎么做?)

  ask by Homunculus Reticulli translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

While the question has been answered, I'd like to add some useful tips when using matplotlib.pyplot.savefig .

(在回答问题后,我想在使用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, you'll find that pylab leaves a generous, often undesirable, whitespace around the image.

(此外,您会发现pylab在图像周围留有大量的空白,通常是不希望有的空白。)

Remove it with:

(使用以下方法删除它:)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...