Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python matplotlib: memory not being released when specifying figure size

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 calling a function similar to this one:

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 of the python process grows by a couple of megabytes with every call to this function. 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 the ram usage grows with time to 600MB. If however I comment out the line figure(figsize=(8,6)) in the function definition, then the ram usage stays steady at 52MB. (8,6) is the default figure size and so identical images are produced in both cases. I'd like to make different sized plots from my numerical data without running out of ram. How might I force python to free up this memory?

I've tried gc.collect() each loop to force garbage collection, and I've tried f = gcf() to get the current figure and then del f to delete it, but to no avail.

I'm running CPython 2.6.5 on 64 bit Ubuntu 10.04.

like image 808
Chris Billington Avatar asked Sep 02 '10 03:09

Chris Billington


People also ask

What is Matplotlib use (' AGG ')?

The last, Agg, is a non-interactive backend that can only write to files. It is used on Linux, if Matplotlib cannot connect to either an X display or a Wayland display.

How do you change the size of a figure in Matplotlib?

Import matplotlib. To change the figure size, use figsize argument and set the width and the height of the plot. Next, we define the data coordinates. To plot a bar chart, use the bar() function. To display the chart, use the show() function.

How do I fix the size of a figure in Python?

Set the figsize Argument First off, the easiest way to change the size of a figure is to use the figsize argument. You can use this argument either in Pyplot's initialization or on an existing Figure object. Here, we've explicitly assigned the return value of the figure() function to a Figure object.


1 Answers

From the docstring for pylab.figure:

In [313]: pylab.figure? 

If you are creating many figures, make sure you explicitly call "close" on the figures you are not using, because this will enable pylab to properly clean up the memory.

So perhaps try:

pylab.close()     # closes the current figure 
like image 128
unutbu Avatar answered Oct 05 '22 16:10

unutbu