0

I am running a python code that produces some figures with Matplotlib and Pandas. After a few runs of the code, I am getting to following error:

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)

I think this is because I forgot to close the figures after each run of the code. I have tried

plt.close('all')

but it does not close the figures from previous sessions. Restarting the terminal (conda) did not help either.

Adriaan
  • 17,741
  • 7
  • 42
  • 75
Kasia
  • 105
  • 6

1 Answers1

0

You have a really similar issue with really good and detailed answers in this thread.

I can tell you that you are probably creating figures in a loop or over and over with more than one execution, so you need to use the methods .clf and .cla to close the figures you are creating. But, you have all the detailed info in the above thread.

  • The solutions in the thread you suggested work on the current run, however, will not close/delete figures open in previous sessions. – Kasia Feb 11 '22 at 09:50
  • Try this solution: run `fig.gcf()` this should close the figure and childs, but it may tell you that this command does not exist. Also found that this other solution worked for other people: plt.show(block=False); time.sleep(5); plt.close('all'). Source: https://github.com/matplotlib/matplotlib/issues/8560/ – Ander Gurtubay Feb 11 '22 at 10:31
  • fig.gcf() did not work, becuase I've been creating figures with pandas: `df.plot.hist()`. without creating fig objects as such (that was apparently a big mistake). The other fix did not work either, unfortunately. – Kasia Feb 11 '22 at 10:42
  • @Kasia If you didn't create a fig object, pandas will automatically create one for you. You can access it via `fig = plt.gcf()` ("get current figure"). If you only want to close the current figure, you can use `plt.clf()`. – JohanC Feb 11 '22 at 13:30
  • Thanks. It turned out that the figures I had open were not figures from previous sessions but figures created in multiple loops on the current session. Adding `plt.close('all')` after each loop solved the problem. @JohanC thanks for the hint about pandas automatically creating fig objects, it is good to know in the future how to access these objects. – Kasia Feb 12 '22 at 10:50