这将在GUI中显示图形:

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

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


当前回答

嗯,我确实建议使用包装器来渲染或控制绘图。示例可以是mpltex(https://github.com/liuyxpp/mpltex)或prettyplotlib(https://github.com/olgabot/prettyplotlib).

import mpltex

@mpltex.acs_decorator
def myplot():
  plt.figure()
  plt.plot(x,y,'b-',lable='xxx')
  plt.tight_layout(pad=0.5)
  plt.savefig('xxxx')  # the figure format was controlled by the decorator, it can be either eps, or pdf or png....
  plt.close()

我基本上经常使用这个装饰器在美国化学学会、美国物理学会、美国光学学会、Elsivier等各种期刊上发表学术论文。

示例如下图所示(https://github.com/MarkMa1990/gradientDescent):

其他回答

您可以使用任何扩展名(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”是您希望保存数字的名称。希望它有帮助:)

正如其他人所说,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()重新打开该图(我自己没有测试)。

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

import matplotlib.image as mpimg

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

使用matplotlib.pyplot.savefig时,可以通过扩展名指定文件格式:

from matplotlib import pyplot as plt

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

这分别提供光栅化或矢量化输出。此外,图像周围有时存在不希望有的空白,可以通过以下方式删除:

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

注意,如果显示绘图,plt.show()应跟随plt.savefig();否则,文件图像将为空。

考虑到今天(提出这个问题时还不可用)许多人使用Jupyter Notebook作为python控制台,有一种极其简单的方法可以将绘图保存为.png,只需从Jupyter记事本调用matplotlib的pylab类,绘制图形“内联”Jupyter单元格,然后将该图形/图像拖到本地目录。别忘了%matplotlib在第一行中内联!