在 python 中关闭图形

rys*_*ink 0 python matplotlib pandas

我正在制作很多图并将它们保存到文件中,一切正常,但在编译过程中我收到以下消息:

RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (`matplotlib.pyplot.figure`) are retained until explicitly closed and may consume too much memory. (To control this warning, see the rcParam `figure.max_open_warning`).
  fig = self.plt.figure(figsize=self.figsize)
Run Code Online (Sandbox Code Playgroud)

所以我认为我可以通过关闭数字来改进代码,我用谷歌搜索并发现我应该使用fig.close(). 但是我收到以下错误'Figure' object has no attribute 'close'。我应该如何让它发挥作用?

这是我创建绘图的循环:

for i in years:
    ax = newdf.plot.barh(y=str(i), rot=0) 
    fig = ax.get_figure()
    fig.savefig('C:\\Users\\rysza\\Desktop\\python data analysis\\zajecia3\\figure'+str(i)+'.jpeg',bbox_inches='tight')
    fig.close()
Run Code Online (Sandbox Code Playgroud)

GPh*_*ilo 8

替换fig.close()plt.close(fig),close是直接在模块中定义的函数。