Python matplotlib: memory not being released when specifying figure size

后端 未结 2 584
我寻月下人不归
我寻月下人不归 2021-02-03 23:28

I\'m using matplotlib to generate many plots of the results of a numerical simulation. The plots are used as frames in a video, and so I\'m generating many of them by repeatedly

2条回答
  •  星月不相逢
    2021-02-03 23:56

    Closing a figure is definitely an option, however, repeated many times, this is time consuming. What I suggest is to have a single persistent figure object (via static function variable, or as additional function argument). If that object is fig, the function will then call fig.clf() before each plotting cycle.

    from matplotlib import pylab as pl
    import numpy as np
    
    TIMES = 10
    x = np.linspace(-10, 10, 100)
    y = np.sin(x)
    def withClose():
        def plotStuff(i):
            fig = pl.figure()
            pl.plot(x, y + x * i, '-k')
            pl.savefig('withClose_%03d.png'%i)
            pl.close(fig)
        for i in range(TIMES):
            plotStuff(i)
    
    
    def withCLF():
        def plotStuff(i):
            if plotStuff.fig is None:
                plotStuff.fig = pl.figure()
            pl.clf()
            pl.plot(x, y + x * i, '-')
            pl.savefig('withCLF_%03d.png'%i)
        plotStuff.fig = None
    
        for i in range(TIMES):
            plotStuff(i)
    

    Here is the timing values

    In [7]: %timeit withClose()
    1 loops, best of 3: 3.05 s per loop
    
    In [8]: %timeit withCLF()
    1 loops, best of 3: 2.24 s per loop
    

提交回复
热议问题