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

我正在编写一个快速脚本来动态生成绘图。 我使用下面的代码(来自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)中,以便可以在批处理脚本中使用它。 我怎么做?


#1楼

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

import matplotlib.image as mpimg

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

#2楼

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

但是我发现在某些情况下总是显示该图 。 (例如,具有Spyder的。 plt.ion()交互模式= ON)我变通的作法迫使图窗口的关闭在我的巨环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

如果需要与您应该能够在以后重新打开图fig.show()没有测试自己)。


#3楼

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

#4楼

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

plt.ioff()

(此命令随科学启动一起自动启动)

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

plt.ion()


#5楼

刚在MatPlotLib文档中找到此链接,正是此链接可解决此问题: http ://matplotlib.org/faq/howto_faq.html#generate-images-without-having-a-window-appear

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

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

我个人仍然更喜欢使用plt.close( fig ) ,因为从那时起,您可以选择隐藏某些图形(在循环过程中),但仍显示图形以进行循环后数据处理。 不过,它可能比选择非交互式后端要慢-如果有人对此进行了测试,那将很有趣。

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

而是使用plt.switch_backend('Agg') ,或在Spyder首选项中关闭“ 启用支持 ”,然后自己运行matplotlib.use('Agg')命令。

从这两个提示: 一 , 二


#6楼

解决方案 :

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


#7楼

我使用了以下内容:

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


#8楼

其他答案是正确的。 但是,有时我发现我想稍后再打开图形对象 。 例如,我可能想更改标签大小,添加网格或进行其他处理。 在理想的情况下,我只需要重新运行生成图的代码并修改设置即可。 las,世界并不完美。 因此,除了保存为PDF或PNG之外,我还添加:

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

这样,以后可以加载图形对象并根据需要操纵设置。

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

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


#9楼

使用plot()和其他函数创建所需的内容之后,可以使用如下子句在打印到屏幕或文件之间进行选择:

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(4, 5))       # size in inches
# 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()

#10楼

您可以执行以下操作:

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

并记得在关闭GUI图之前先让savefig完成。 这样,您可以预先查看图像。

或者,您可以使用plt.show()查看它,然后关闭GUI并再次运行脚本,但是这次将plt.show()替换为plt.savefig()

或者,您可以使用

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

#11楼

#write the code for the plot     
plt.savefig("filename.png")

该文件将与运行的python / Jupyter文件保存在同一目录中


#12楼

根据问题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()


#13楼

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

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


#14楼

鉴于今天(提出此问题时尚不可用)许多人将Jupyter Notebook用作python控制台,所以有一种极为简单的方法将图另存为.png ,只需从Jupyter Notebook调用matplotlibpylab类,就可以图形“内联” jupyter单元格,然后将该图形/图像拖到本地目录。 不要忘记第一行%matplotlib inline


#15楼

您可以使用任何扩展名(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”是您要用来保存图形的名称。 希望能帮助到你:)


#16楼

除了上述内容外,我还添加了__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'

最后的提示在这里找到。


#17楼

您可以这样做:

def plotAFig():
  plt.figure()
  plt.plot(x,y,'b-')
  plt.savefig("figurename.png")
  plt.close()

#18楼

解决方案是:

pylab.savefig('foo.png')

#19楼

在回答问题后,我想在使用matplotlib.pyplot.savefig时添加一些有用的提示。 文件格式可以通过扩展名指定:

from matplotlib import pyplot as plt

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

将分别给出栅格化或矢量化的输出,这两个都可能有用。 此外,您会发现pylab在图像周围留有大量的空白,通常是不希望有的空白。 使用以下方法删除它:

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

你可能感兴趣的:(python,matplotlib,plot)