title: How can I release memory after creating matplotlib figures
body: <p>I have several matlpotlib functions rolled into some django-celery tasks.</p>
  
  <p>Every time the tasks are called more RAM is dedicated to python. Before too long, python is taking up all of the RAM.</p>
  
  <p><strong>QUESTION:</strong> How can I release this memory?</p>
  
  <p><strong>UPDATE 2 - A Second Solution:</strong></p>
  
  <p>I asked a similar question specifically about the memory locked up when matplotlib errors, but I got a good answer to this question <code>.clf()</code>, <code>.close()</code>, and <code>gc.collect()</code> aren't needed if you use multiprocess to run the plotting function in a separate process whose memory will automatically be freed once the process ends.</p>
  
  <p><a href="https://stackoverflow.com/questions/7125710/matplotlib-errors-result-in-a-memory-leak-how-can-i-free-up-that-memory">Matplotlib errors result in a memory leak. How can I free up that memory?</a></p>
  
  <p><strong>UPDATE - The Solution:</strong></p>
  
  <p>These stackoverflow posts suggested that I can release the memory used by matplotlib objects with the following commands:</p>
  
  <p><code>.clf()</code>: <a href="https://stackoverflow.com/questions/2364945/matplotlib-runs-out-of-memory-when-plotting-in-a-loop-edited">Matplotlib runs out of memory when plotting in a loop</a></p>
  
  <p><code>.close()</code>: <a href="https://stackoverflow.com/questions/3623600/python-matplotlib-memory-not-being-released-when-specifying-figure-size">Python matplotlib: memory not being released when specifying figure size</a></p>
  
  <pre><code>import gc
  gc.collect()
  </code></pre>
  
  <p>Here is the example I used to test the solution:</p>
  
  <pre><code>import matplotlib
  matplotlib.use('Agg')
  import matplotlib.pyplot as plt
  from pylab import import figure, savefig
  import numpy as np
  import gc      
  
  a = np.arange(1000000)
  b = np.random.randn(1000000)
  
  fig = plt.figure(num=1, dpi=100, facecolor='w', edgecolor='w')
  fig.set_size_inches(10,7)
  ax = fig.add_subplot(111)
  ax.plot(a, b)
  
  fig.clf()
  plt.close()
  del a, b
  gc.collect()
  </code></pre>