Python matplotlib: memory not allocated when setting shape size

I use matplotlib to generate many graphs of numerical simulation results. Graphs are used as frames in the video, and so I generate many of them by repeatedly calling a function similar to this:

from pylab import * def plot_density(filename,i,t,psi_Na): figure(figsize=(8,6)) imshow(abs(psi_Na)**2,origin = 'lower') savefig(filename + '_%04d.png'%i) clf() 

The problem is that the memory usage for the python process increases by a couple megabytes each time this function is called. For example, if I call it with this loop:

 if __name__ == "__main__": x = linspace(-6e-6,6e-6,128,endpoint=False) y = linspace(-6e-6,6e-6,128,endpoint=False) X,Y = meshgrid(x,y) k = 1000000 omega = 200 times = linspace(0,100e-3,100,endpoint=False) for i,t in enumerate(times): psi_Na = sin(k*X-omega*t) plot_density('wavefunction',i,t,psi_Na) print i 

then plunger usage grows with time to 600 MB. If, however, I comment on the line figure(figsize=(8,6)) in the definition of the function, then the use of the plunger remains stable at 52 MB. (8,6) is the default shape size, and therefore the same image is created in both cases. I would like to make graphs of different sizes from my numerical data without being exhausted. How can I get python to free this memory?

I tried gc.collect() every cycle to force garbage collection, and I tried f = gcf() to get the current digit and then del f to delete it, but to no avail.

I am running CPython 2.6.5 on 64 bit Ubuntu 10.04.

+25
python memory-management matplotlib
Sep 02 2018-10-09T00:
source share
2 answers

From docstring for pylab.figure :

 In [313]: pylab.figure? 

If you are creating a lot of digits, make sure you explicitly call “close” the digits you are not using, because this will allow pylab to clear the memory correctly.

So try:

 pylab.close() # closes the current figure 
+35
Sep 02 '10 at 3:17
source share

Closing a figure is definitely an option, however, it repeats many times, it takes a lot of time. I suggest having one permanent shape object (via a static function variable or as an optional function argument). If this object is fig , the function will then call fig.clf() before each fig.clf() 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) 

Below are the time 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 
+9
Dec 14 '11 at 9:03
source share



All Articles