Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closing a figure in python

I am making a lot of plots and saving them to a file, it all works, but during the compilation I get the following message:

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)

So I think I could improve the code by closing the figures, I googled it and found that I should use fig.close(). However I get the following error 'Figure' object has no attribute 'close'. How should I make it work?

This is the loop in which I create plots:

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()
like image 240
ryszard eggink Avatar asked Oct 23 '25 11:10

ryszard eggink


2 Answers

Replace fig.close() with plt.close(fig), close is a function defined directly in the module.

like image 101
GPhilo Avatar answered Oct 26 '25 00:10

GPhilo


Try this, matplotlib.pyplot.close(fig) , for more information refer this website https://matplotlib.org/2.1.0/api/_as_gen/matplotlib.pyplot.close.html

like image 30
ssb Avatar answered Oct 26 '25 00:10

ssb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!