5

I need to create lots of figures, then use savefig to save the figure.

But after about 280 pictures, it throws the exception RuntimeError: Could not allocate memory for image

Is there some function like clear() in Matplotlib ?

MackM
  • 2,906
  • 5
  • 31
  • 45
cxlove
  • 71
  • 1
  • 1
  • 3
  • Reassign any variables referring to your pictures and Python should clear the memory for you. – grc Nov 17 '14 at 06:57
  • 1
    Are you using a single figure object or creating many figures? – Thibaut Nov 17 '14 at 06:59
  • 1
    possible duplicate of [Matplotlib runs out of memory when plotting in a loop](http://stackoverflow.com/questions/2364945/matplotlib-runs-out-of-memory-when-plotting-in-a-loop) – sebix Nov 17 '14 at 19:12

2 Answers2

7

Yes, you can use:

MackM
  • 2,906
  • 5
  • 31
  • 45
g-abello
  • 137
  • 8
  • dont forget https://stackoverflow.com/questions/20401057/matplotlib-close-does-not-close-the-window : see were it says : Remember that plt.show() is a blocking function, so in the example code you used above, plt.close() isn't being executed until the window is closed, which makes it redundant. You can use plt.ion() at the beginning of your code to make it non-blocking, although this has other implications. – pippo1980 Dec 06 '21 at 19:38
0

You can try:

i=1
while i<=280:
    plt.figure(i).clear()
    i+=1

But you have to numbered your figures:

import matplotlib.pyplot as plt
from numpy import *

# example of data:
x = linspace(0,4,1e3)
data = sin(10*x)

plt.figure(1)
plt.plot(x, data)
plt.show()