这将在GUI中显示图形:

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

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


当前回答

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

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

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

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

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

其他回答

根据问题Matplotlib(pyplot)savefig输出空白图像。

有一点需要注意:如果您使用plt.show,并且它应该在plt.savefig之后,否则您将给出一个空白图像。

详细示例:

import numpy as np
import matplotlib.pyplot as plt


def draw_result(lst_iter, lst_loss, lst_acc, title):
    plt.plot(lst_iter, lst_loss, '-b', label='loss')
    plt.plot(lst_iter, lst_acc, '-r', label='accuracy')

    plt.xlabel("n iteration")
    plt.legend(loc='upper left')
    plt.title(title)
    plt.savefig(title+".png")  # should before plt.show method

    plt.show()


def test_draw():
    lst_iter = range(100)
    lst_loss = [0.01 * i + 0.01 * i ** 2 for i in xrange(100)]
    # lst_loss = np.random.randn(1, 100).reshape((100, ))
    lst_acc = [0.01 * i - 0.01 * i ** 2 for i in xrange(100)]
    # lst_acc = np.random.randn(1, 100).reshape((100, ))
    draw_result(lst_iter, lst_loss, lst_acc, "sgd_method")


if __name__ == '__main__':
    test_draw()

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

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

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

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

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

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

import matplotlib.image as mpimg

img = mpimg.imread("src.png")
mpimg.imsave("out.png", img)

解决方案是:

pylab.savefig('foo.png')

解决方案:

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

之后导入matplotlib