这将在GUI中显示图形:

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

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


当前回答

import matplotlib.pyplot as plt
plt.savefig("image.png")

在Jupyter Notebook中,您必须在一个单元格中删除plt.show()并添加plt.savefig()以及其他plt代码。图像仍将显示在笔记本中。

其他回答

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

然而,我发现在某些情况下,数字总是显示出来的。(例如,Spyder具有plt.ion():交互式模式=打开。)强制关闭图形窗口:

plt.close(figure_object)

(参见文档)。这样,在一个大循环中,我就不会有一百万个未结数字。示例用法:

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 window

如果需要,您可以稍后使用图show()重新打开该图(我自己没有测试)。

您可以使用任何扩展名(png、jpg等)和所需的分辨率保存图像。这里有一个功能来保存您的身材。

import os

def save_fig(fig_id, tight_layout=True, fig_extension="png", resolution=300):
    path = os.path.join(IMAGES_PATH, fig_id + "." + fig_extension)
    print("Saving figure", fig_id)
    if tight_layout:
        plt.tight_layout()
    plt.savefig(path, format=fig_extension, dpi=resolution)

“fig_id”是您希望保存数字的名称。希望它有帮助:)

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()

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

plt.ioff()

(此命令在科学启动时自动启动)

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

plt.ion()

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

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

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

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

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