Matplotlib runs out of memory when plotting in a loop

Is each loop supposed to generate a new figure? I don’t see you closing it or creating a new figure instance from loop to loop.

This call will clear the current figure after you save it at the end of the loop:

pyplot.clf()

I’d refactor, though, and make your code more OO and create a new figure instance on each loop:

from matplotlib import pyplot

while True:
  fig = pyplot.figure()
  ax = fig.add_subplot(111)
  ax.plot(x,y)
  ax.legend(legendStrings, loc="best")
  fig.savefig('himom.png')
  # etc....

Leave a Comment