title: Memory Leak in Matplotlib save fig with PDFPages
body: <p>EDIT: UPDATE</p>
  
  <p>I used <code>objgraph</code> to print out <a href="http://imgur.com/a/ebYpJ" rel="nofollow">back reference graphs</a> for the <code>'Reference'</code> items that appeared in the memory leak. It seems that PdfPages is holding onto all of the images as I iterate thorough them and save them to each page (so perhaps something just inherent to the PdfPages module). I think I'm going to modify my code to write a small PDF file on each iteration and then use <code>pypdf</code> to merge these files into my desired larger PDF file.</p>
  
  <p>EDIT: I am running Python 2.7.3 with Matplotlib 1.3.1. I have tried printing out  <code>gc.garbage</code>, but this returns an empty list, so it doesn't appear that there are any uncollectable objects. I have also tried using both the PDF and Agg backends, but the memory leak is still present in both of these. I tried specifically closing the axes (<code>ax1</code> and <code>cbaxes1</code>) and explicitly using <code>del</code> on all of the variables (which had the effect of removing the +3 list after closing but increasing the +2 list after saving to a +5 list).</p>
  
  <p>I am trying to create multiple heatmaps via pcolormesh and save them to a single page in a PDF and repeat this process to create multiple pages with figures in the PDF file (I've dropped it down to only one figure per page for the sake of this example). </p>
  
  <p>There seems to be a memory leak occurring with the savefig function, which seems small at first, but really adds up as I want to be able to save very large PDF files.</p>
  
  <pre><code>import matplotlib
  matplotlib.use('Agg')
  import matplotlib.pyplot as plt
  from matplotlib.backends.backend_pdf import PdfPages
  from matplotlib import gridspec
  from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
  import numpy as np
  
  import resource
  import gc
  import objgraph
  
  def plotfunction(i,pdf):
  
      fig = plt.figure()
      fig.set_figheight(25)
      fig.set_figwidth(64)
  
      gs = gridspec.GridSpec(1,2)
      ax1 = plt.subplot(gs[0],rasterized=True)
  
      heatmap1 = ax1.pcolormesh(np.random.uniform(size=(10,10)))
  
      cbaxes1 = plt.subplot(gs[1],rasterized=True)
  
      cb1 = plt.colorbar(heatmap1, cax= cbaxes1, use_gridspec = True)
  
      gc.collect()
  
      print 'Memory Growth before savefig  {round}: %s ({mb} MB)' .format(round=i,mb=resource.getrusage(resource.RUSAGE_SELF).ru_maxrss/1024/1024) % resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
      objgraph.show_growth()
  
      pdf.savefig(fig) # the memory leak seems to occur here
  
      gc.collect()
  
      print 'Memory Growth after savefig  {round}: %s ({mb} MB)' .format(round=i,mb=resource.getrusage(resource.RUSAGE_SELF).ru_maxrss/1024/1024) % resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
      objgraph.show_growth()
  
      fig.clf()
      plt.close(fig)
      plt.close('all')
      gc.collect()
  
      print 'Memory Growth after closing  {round}: %s ({mb} MB)' .format(round=i,mb=resource.getrusage(resource.RUSAGE_SELF).ru_maxrss/1024/1024) % resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
      objgraph.show_growth()
  
  
  def main():
  
      pdf = PdfPages('output.pdf')
      for i in range(15):
          plotfunction(i,pdf)
          print 'Memory Growth outside function {round}: %s ({mb} MB)' .format(round=i,mb=resource.getrusage(resource.RUSAGE_SELF).ru_maxrss/1024/1024) % resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
          gc.collect()
          objgraph.show_growth()
      pdf.close()
  
  if __name__ == "__main__":
  
      main()
  </code></pre>
  
  <p>Here's the output showing the memory leak:</p>
  
  <pre><code>Memory Growth before savefig  7: 877674496 (837 MB)
  Memory Growth after savefig  7: 988385280 (942 MB)
  Reference       32        +3
  list          1839        +2
  Name            16        +2
  tuple         2384        +2
  Memory Growth after closing  7: 988385280 (942 MB)
  list     1842        +3
  Memory Growth outside function 7: 988385280 (942 MB)
  Memory Growth before savefig  8: 988651520 (942 MB)
  Memory Growth after savefig  8: 1099231232 (1048 MB)
  Reference       35        +3
  list          1844        +2
  Name            18        +2
  tuple         2386        +2
  Memory Growth after closing  8: 1099231232 (1048 MB)
  list     1847        +3
  Memory Growth outside function 8: 1099231232 (1048 MB)
  </code></pre>
  
  <p>I have tried using multiprocessing, avoiding pyplot, and moving the save into another function as suggested in other posts, but none of these solutions have solved the memory leak problem.</p>
  
  <p>Thanks.</p>