这将在GUI中显示图形:

import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [1, 4, 9])
plt.show()

但我如何将图形保存到文件(例如foo.png)中?


当前回答

除上述内容外,我还为名称添加了__file__,以便图片和Python文件获得相同的名称。我还添加了一些参数以使它看起来更好:

# Saves a PNG file of the current graph to the folder and updates it every time
# (nameOfimage, dpi=(sizeOfimage),Keeps_Labels_From_Disappearing)
plt.savefig(__file__+".png",dpi=(250), bbox_inches='tight')
# Hard coded name: './test.png'

其他回答

刚刚在MatPlotLib文档中找到了解决此问题的链接:http://matplotlib.org/faq/howto_faq.html#generate-图像-无窗口外观

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

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

我个人还是更喜欢使用plt.close(图),因为这样你就可以选择隐藏某些数字(在循环期间),但仍然可以显示循环后数据处理的数字。它可能比选择非交互式后端要慢——如果有人测试了它,那会很有趣。

UPDATE:对于Spyder,通常不能以这种方式设置后端(因为Spyder通常会提前加载matplotlib,从而阻止您使用matplotlib.use())。

相反,请使用plt.switch_backend('Agg'),或在Spyder prefs中关闭“enable support”,然后自己运行matplotlib.use('Agg')命令。

从这两个提示中:一、二

其他答案是正确的。然而,我有时发现我想稍后打开地物对象。例如,我可能希望更改标签大小、添加网格或执行其他处理。在一个完美的世界里,我只需重新运行生成情节的代码,并调整设置。唉,世界并不完美。因此,除了保存为PDF或PNG外,我还添加了:

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

像这样,我可以稍后加载地物对象并根据需要操作设置。

我还为堆栈中的每个函数/方法编写了带有源代码和locals()字典的堆栈,以便稍后可以确切地知道是什么生成了该图。

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

使用matplotlib.pyplot时,必须先保存绘图,然后使用以下两行关闭绘图:

fig.savefig('plot.png') # save the plot, place the path you want to save the figure in quotation
plt.close(fig) # close the figure window
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()

解决方案是:

pylab.savefig('foo.png')