这将在GUI中显示图形:
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [1, 4, 9])
plt.show()
但我如何将图形保存到文件(例如foo.png)中?
这将在GUI中显示图形:
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [1, 4, 9])
plt.show()
但我如何将图形保存到文件(例如foo.png)中?
当前回答
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,只需从Jupyter记事本调用matplotlib的pylab类,绘制图形“内联”Jupyter单元格,然后将该图形/图像拖到本地目录。别忘了%matplotlib在第一行中内联!
正如其他人所说,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()重新打开该图(我自己没有测试)。
除上述内容外,我还为名称添加了__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'
没有什么对我有用。问题是保存的图像很小,我找不到它是怎么变大的。
这似乎使它更大,但仍然不是全屏。
https://matplotlib.org/stable/api/figure_api.html#matplotlib.figure.Figure.set_size_inches
图set_size_inches((宽,高))
希望这对某人有所帮助。
您可以执行以下任一操作:
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')