-1

I am using Python and the matplotlib library.

I run through a very long code creating multiple figures along the way.

I do something like this, many many times:

plt.figure()
plt.plot(x, y)
plt.grid('on')
plt.close()

Then, at some point, I get the error:

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.

The error is clear to me, but: I do call "plt.close()".

Now that I am writing this I am realizing that maybe plt.close() has to take a specific qualifier for what figure to close? Like plt.close(1) etc. I guess I can use plt.close('all'), but what if I just want to close the most recent figure?

Jesper - jtk.eth
  • 7,026
  • 11
  • 36
  • 63
  • 1
    See https://stackoverflow.com/questions/21884271/warning-about-too-many-open-figures – Outis Mar 30 '17 at 17:35
  • I believe you don't need to call plt.figure(). Can you try without that code line and let us know? – Cedric Zoppolo Mar 30 '17 at 17:40
  • @Outis, thanks for your response. So I read the link and not really sure still why it does not work: plt.close() "closes a window, which will be the current window" ? Do you know what is happening? – Jesper - jtk.eth Mar 30 '17 at 17:51
  • when to do you actually get the recursion error? the warning you posted seems unrelated. – Paul H Mar 30 '17 at 18:06
  • Well imagine that code wrapped around a loop, as I say before the code itself: I call that snipped many many times. – Jesper - jtk.eth Mar 30 '17 at 18:06

2 Answers2

1

The code from the question should work fine. Since you close the figure in every loop step, there will only ever be one single figure open.

Minimal example, which does not produce any error:

import matplotlib.pyplot as plt

for i in range(30):
    plt.figure()
    plt.plot(range(i+3), range(i+3))
    plt.grid('on')
    plt.close()

plt.show() # doesn't show anything since no figure is open

So the reason for the error must be somewhere else in the code.

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
  • Actually, when I commented out the "plt.close()" I got the error. So you're right: I must have overlooked something in the code. Thank you. – Jesper - jtk.eth Apr 21 '17 at 00:58
0

You should operate on matplotlib objects directly. It's so much less ambiguous:

fig, ax = plt.subplots()
ax.plot(x, y)
...
plt.close(fig)
Paul H
  • 65,268
  • 20
  • 159
  • 136
  • Just because I have a lot of plt.figure() calls and following plt.(...), can I get away with: fig = plt.figure() plt.plot(x, y) plt.close(fig) – Jesper - jtk.eth Mar 30 '17 at 18:05
  • 1
    yeah, but i don't know why you'd want to. shifts mental burden from the computer to yourself. if you're repeating this code a lot, write a function. – Paul H Mar 30 '17 at 18:28