这将在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)中?
当前回答
使用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
其他回答
正如其他人所说,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()重新打开该图(我自己没有测试)。
使用plot()和其他函数创建所需的内容后,可以使用如下子句在绘制到屏幕或文件之间进行选择:
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(4, 5)) # size in inches
# use plot(), etc. to create your plot.
# Pick one of the following lines to uncomment
# save_file = None
# save_file = os.path.join(your_directory, your_file_name)
if save_file:
plt.savefig(save_file)
plt.close(fig)
else:
plt.show()
由于服务器上没有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 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
使用matplotlib.pyplot.savefig时,可以通过扩展名指定文件格式:
from matplotlib import pyplot as plt
plt.savefig('foo.png')
plt.savefig('foo.pdf')
这分别提供光栅化或矢量化输出。此外,图像周围有时存在不希望有的空白,可以通过以下方式删除:
plt.savefig('foo.png', bbox_inches='tight')
注意,如果显示绘图,plt.show()应跟随plt.savefig();否则,文件图像将为空。