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()
鉴于今天(在提出这个问题时不可用)很多人使用Jupyter Notebook作为python控制台,有一种非常简单的方法来保存这些图 .png ,只需拨打电话 matplotlib 的 pylab 来自Jupyter Notebook的类,绘制图形'内联'jupyter单元格,然后将该图形/图像拖动到本地目录。别忘了 %matplotlib inline 在第一行!
.png
matplotlib
pylab
%matplotlib inline
如果像我一样使用Spyder IDE,则必须禁用交互模式:
plt.ioff()
(此命令随科学启动自动启动)
如果要再次启用它,请使用:
plt.ion()
根据问题 Matplotlib(pyplot)savefig输出空白图像 。
有一点需要注意:如果你使用 plt.show 它应该在之后 plt.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()
import matplotlib.pyplot as plt plt.savefig("image.png")
在Jupyter笔记本中你必须删除 plt.show() 并添加 plt.savefig() ,以及一个单元格中的其余plt-code。 图像仍将显示在笔记本中。
plt.show()
plt.savefig()
你可以这样做:
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')
虽然问题已得到解答,但我想在使用时添加一些有用的提示 matplotlib.pyplot.savefig 。文件格式可以通过扩展名指定:
from matplotlib import pyplot as mp mp.savefig('foo.png') mp.savefig('foo.pdf')
将分别给出栅格化或矢量化输出,两者都可能有用。另外,你会发现的 pylab 在图像周围留下了一个慷慨的,通常是不受欢迎的空白空间。删除它:
savefig('foo.png', bbox_inches='tight')
如果您不喜欢“当前”图的概念,请执行以下操作:
import matplotlib.image as mpimg img = mpimg.imread("src.png") mpimg.imsave("out.png", img)
#write the code for the plot plt.savefig("filename.png")
该文件将保存在与运行的python / Jupyter文件相同的目录中