这将在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()
其他回答
使用matplotlib.pyplot时,必须先保存绘图,然后使用以下两行关闭绘图:
fig.savefig('plot.png') # save the plot, place the path you want to save the figure in quotation
plt.close(fig) # close the figure window
解决方案:
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
其他答案是正确的。然而,我有时发现我想稍后打开地物对象。例如,我可能希望更改标签大小、添加网格或执行其他处理。在一个完美的世界里,我只需重新运行生成情节的代码,并调整设置。唉,世界并不完美。因此,除了保存为PDF或PNG外,我还添加了:
with open('some_file.pkl', "wb") as fp:
pickle.dump(fig, fp, protocol=4)
像这样,我可以稍后加载地物对象并根据需要操作设置。
我还为堆栈中的每个函数/方法编写了带有源代码和locals()字典的堆栈,以便稍后可以确切地知道是什么生成了该图。
注意:要小心,因为有时这种方法会生成巨大的文件。
如果像我一样使用Spyder IDE,则必须禁用交互模式:
plt.ioff()
(此命令在科学启动时自动启动)
如果要再次启用,请使用:
plt.ion()
import matplotlib.pyplot as plt
plt.savefig("image.png")
在Jupyter Notebook中,您必须在一个单元格中删除plt.show()并添加plt.savefig()以及其他plt代码。图像仍将显示在笔记本中。