memory leak for GTKAgg animation

Hi John -
Yes thanks again! This did it. Plus it is a valuable lesson
- it never occurred to me to look at the base class to find
more useful methods. To make this cleaner I will post the
complete simple working example after this message.


-----Original Message-----
From: John Hunter [mailto:jdh2358@…287…]
Sent: Sunday, February 14, 2010 7:39 PM
To: John Jameson
Cc:; Michael Droettboom
Subject: Re: [Matplotlib-users] memory leak for GTKAgg animation

On Sat, Feb 13, 2010 at 2:53 PM, John Jameson <jjameson@...2972...> wrote:

I find the very basic animation below has a memory leak (my pagefile usage
number keeps growing in the Windows XP Windows Task Manager Performance
graph).I don't see this with the "" example on:

(which I used as a starting point for this). In ""


set_ydata() routine is used to update the line for the animation and this
does not leak. But if you call plot again with the new y_data (instead of
using set_ydata), this leaks too. Anyone have an idea on how to stop the

This isn't a memory leak. The problem is that you keep adding new
patches to the axes when you want just one with different data. Eg,
in your loop, run this code, and you will see that the number of
patches is growing:

   x_cir = 1.0 + 0.003*update_line.cnt
   cir = CirclePolygon((x_cir, 1), 0.3, animated=True, \
                   resolution=12, lw=2 )
   print 'num patches=%d, mem usage=%d'%(
       len(ax.patches), cbook.report_memory(update_line.cnt))

You should add just one patch and then manipulate the data. In this
case, you are using a CirclePolygon which derives from RegularPolygon
and so you can update the "xy" property

But on testing this it looks like there is a bug in that the set_xy
property setter is ignored. I worked around this in the func below by
setting the private variable directly, but this looks like a bug we
need to fix (Michael, shouldn't we respect the xy passed in in
patches.RegularPolygon._set_xy ?). In the meantime, the following
workaround should work for you w/o leaking....

def update_line():
   global x, y
   print update_line.cnt
   if update_line.background is None:
       update_line.background = canvas.copy_from_bbox(ax.bbox)

   x_cir = 1.0 + 0.003*update_line.cnt

   if update_line.cir is None:
       cir = CirclePolygon((x_cir, 1), 0.3, animated=True, \
                   resolution=12, lw=2 )
       update_line.cir = cir
       update_line.cir._xy = x_cir, 1
   print 'num patches=%d, xy=%s, mem usage=%d'%(
       len(ax.patches), update_line.cir.xy,

   if update_line.direction == 0:
       update_line.cnt += 1
       if update_line.cnt > 500:
           update_line.direction = 1
       update_line.cnt -= 1
       if update_line.cnt < 100:
           update_line.direction = 0

   return update_line.cnt<100

update_line.cnt = 0
update_line.direction = 0
update_line.background = None
update_line.cir = None