保存绘图到图像文件,而不是使用Matplotlib显示它

我正在写一个快速而肮脏的脚本来dynamic地生成剧情。 我正在使用下面的代码(来自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),例如,它可以在批处理脚本中使用。 我怎么做?

虽然这个问题已经得到解答,但是我想在使用savefig的时候添加一些有用的技巧。 文件格式可以由扩展名指定:

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

将分别给出一个光栅化或向量化的输出,这可能是有用的。 另外,你会发现pylab在图像周围留下了一个慷慨的,往往是不希望有的空白。 删除它:

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

解决scheme是:

 pylab.savefig('foo.png') 

正如其他人所说, plt.savefig()fig1.savefig()确实是保存图像的方式。

但是我发现在某些情况下(例如Spyder有plt.ion() :interactive mode = On),总是显示数字。 我通过强制在巨型循环中closures数字窗口来解决这个问题,所以在循环中我没有一百万的开放数字:

 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 

刚刚在MatPlotLib文档中发现了这个链接,正是这个问题: http ://matplotlib.org/faq/howto_faq.html#generate-images-without-having-a-window-appear

他们说最简单的方法是通过matplotib.use(<backend>)使用非交互式后端(如Agg matplotib.use(<backend>) ,例如:

 import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt plt.plot([1,2,3]) plt.savefig('myfig') 

我个人更喜欢使用plt.close( fig ) ,因为你可以select隐藏某些数字(循环过程中),但是仍然会显示循环后数据处理的数据。 这可能比select一个非交互式的后端要慢 – 如果有人testing过,会很有趣。

如果您不喜欢“当前”数字的概念,请执行以下操作:

 import matplotlib.image as mpimg img = mpimg.imread("src.png") mpimg.imsave("out.png", img) 

其他答案是正确的。 不过,我有时会发现我想打开graphics对象 。 例如,我可能想要更改标签大小,添加网格或执行其他处理。 在一个完美的世界中,我只是简单地重新运行生成剧情的代码,并调整设置。 唉,世界并不完美。 因此,除了保存为PDF或PNG,我补充:

 with open('some_file.pkl', "wb") as fp: pickle.dump(fig, fp, protocol=4) 

像这样,我可以稍后加载graphics对象并按照我的意愿操作设置。

我还为堆栈中的每个函数/方法使用源代码和locals()字典编写了堆栈,以便稍后可以确切地说明生成该图的内容。

注意:小心,因为有时这种方法会产生巨大的文件。

 import datetime import numpy as np from matplotlib.backends.backend_pdf import PdfPages import matplotlib.pyplot as plt # Create the PdfPages object to which we will save the pages: # The with statement makes sure that the PdfPages object is closed properly at # the end of the block, even if an Exception occurs. with PdfPages('multipage_pdf.pdf') as pdf: plt.figure(figsize=(3, 3)) plt.plot(range(7), [3, 1, 4, 1, 5, 9, 2], 'r-o') plt.title('Page One') pdf.savefig() # saves the current figure into a pdf page plt.close() plt.rc('text', usetex=True) plt.figure(figsize=(8, 6)) x = np.arange(0, 5, 0.1) plt.plot(x, np.sin(x), 'b-') plt.title('Page Two') pdf.savefig() plt.close() plt.rc('text', usetex=False) fig = plt.figure(figsize=(4, 5)) plt.plot(x, x*x, 'ko') plt.title('Page Three') pdf.savefig(fig) # or you can pass a Figure object to pdf.savefig plt.close() # We can also set the file's metadata via the PdfPages object: d = pdf.infodict() d['Title'] = 'Multipage PDF Example' d['Author'] = u'Jouni K. Sepp\xe4nen' d['Subject'] = 'How to create a multipage pdf file and set its metadata' d['Keywords'] = 'PdfPages multipage keywords author title subject' d['CreationDate'] = datetime.datetime(2009, 11, 13) d['ModDate'] = datetime.datetime.today() 

我使用了以下内容:

 import matplotlib.pyplot as plt p1 = plt.plot(dates, temp, 'r-', label="Temperature (celsius)") p2 = plt.plot(dates, psal, 'b-', label="Salinity (psu)") plt.legend(loc='upper center', numpoints=1, bbox_to_anchor=(0.5, -0.05), ncol=2, fancybox=True, shadow=True) plt.savefig('data.png') plt.show() f.close() plt.close() 

保存完图后我发现使用plt.show非常重要,否则不起作用。 数字出口在PNG

在使用plot()和其他函数来创build你想要的内容之后,你可以使用这样一个子句来select在绘制到屏幕还是文件之间:

 import matplotlib.pyplot as plt fig = plt.figure(figuresize=4, 5) # use plot(), etc. to create your plot. # Pick one of the following lines to uncomment # save_file = None # save_file = os.path.join(your_directory, your_file_name) if save_file: plt.savefig(save_file) plt.close(fig) else: plt.show() 

如果像我一样使用Spyder IDE,则必须禁用交互模式:

plt.ioff()

(这个命令是在科学启动时自动启动的)

如果要再次启用它,请使用:

plt.ion()

解决scheme :

 import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib matplotlib.style.use('ggplot') ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000)) ts = ts.cumsum() plt.figure() ts.plot() plt.savefig("foo.png", bbox_inches='tight') 

如果您想要显示图像并保存图像,请使用:

 %matplotlib inline 

import matplotlib

你可以做:

 plt.show(hold=False) plt.savefig('name.pdf') 

并记得在closuresGUI图之前让savefig完成。 这样你可以预先看到图像。

或者,你可以用plt.show()来查看它。然后closuresGUI并再次运行脚本,但这次用plt.show()replaceplt.savefig()

或者,您可以使用

 fig, ax = plt.figure(nrows=1, ncols=1) plt.plot(...) plt.show() fig.savefig('out.pdf')