这将在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)中?
当前回答
正如其他人所说,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()重新打开该图(我自己没有测试)。
其他回答
正如其他人所说,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()重新打开该图(我自己没有测试)。
您可以使用任何扩展名(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”是您希望保存数字的名称。希望它有帮助:)
如果您不喜欢“当前”数字的概念,请执行以下操作:
import matplotlib.image as mpimg
img = mpimg.imread("src.png")
mpimg.imsave("out.png", img)
除上述内容外,我还为名称添加了__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'
解决方案:
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