Matplotlib runs out of memory when plotting in a loop

后端 未结 3 1814
北海茫月
北海茫月 2020-11-28 12:07

I have a fairly simple plotting routine that looks like this:

from __future__ import division
import datetime
import matplotlib
matplotlib.use(\'Agg\')
from          


        
相关标签:
3条回答
  • 2020-11-28 12:16

    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....
    
    0 讨论(0)
  • 2020-11-28 12:35

    I've also run into this error. what seems to have fixed it is

    while True:
        fig = pyplot.figure()
        ax = fig.add_subplot(111)
        ax.plot(x,y)
        ax.legend(legendStrings, loc = 'best')
        fig.savefig('himom.png')
        #new bit here
        pylab.close(fig) #where f is the figure
    

    running my loop stably now with fluctuating memory but no consistant increase

    0 讨论(0)
  • 2020-11-28 12:39

    Answer from ninjasmith worked for me too - pyplot.close() enabled my loops to work.

    From the pyplot tutorial, Working with multiple figures and axes:

    You can clear the current figure with clf() and the current axes with cla(). If you find this statefulness, annoying, don’t despair, this is just a thin stateful wrapper around an object oriented API, which you can use instead (see Artist tutorial)

    If you are making a long sequence of figures, you need to be aware of one more thing: the memory required for a figure is not completely released until the figure is explicitly closed with close(). Deleting all references to the figure, and/or using the window manager to kill the window in which the figure appears on the screen, is not enough, because pyplot maintains internal references until close() is called.

    0 讨论(0)
提交回复
热议问题