将绘图保存到图像文件,而不是使用Matplotlib显示它 [英] Save plot to image file instead of displaying it using 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?
推荐答案
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')
将分别给出栅格化或矢量化的输出,这两个都可能有用.此外,您会发现pylab
在图像周围留有大量的空白,通常是不希望有的空白.删除它:
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. Remove it with:
savefig('foo.png', bbox_inches='tight')
这篇关于将绘图保存到图像文件,而不是使用Matplotlib显示它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!