这将在GUI中显示图形:

import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [1, 4, 9])
plt.show()

但我如何将图形保存到文件(例如foo.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

其他回答

解决方案:

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

没有什么对我有用。问题是保存的图像很小,我找不到它是怎么变大的。

这似乎使它更大,但仍然不是全屏。

https://matplotlib.org/stable/api/figure_api.html#matplotlib.figure.Figure.set_size_inches

图set_size_inches((宽,高))

希望这对某人有所帮助。

由于服务器上没有gui,因此使用“agg”。使用gui和VSC在ubuntu 21.10上进行调试。在调试中,尝试显示绘图,然后保存到web UI的文件。

发现显示前需要保存,否则保存的绘图为空。我想这场演出会因为某种原因使剧情明朗化。执行以下操作:

plt.savefig(imagePath) 
plt.show()
plt.close(fig)

而不是:

plt.show()
plt.savefig(imagePath) 
plt.close(fig)

如前所述,您可以使用:

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

用于保存您正在显示的任何IPhython图像。或者换个角度(从不同的角度看),如果你曾经使用过open cv,或者你已经导入了open cv的话,你可以去:

import cv2

cv2.imwrite("myfig.png",image)

但这只是为了以防万一,如果您需要使用OpenCV。否则plt.savefig()就足够了。

正如其他人所说,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()重新打开该图(我自己没有测试)。