Problem in animation cookbook example

I believe I’ve found a problem with the following cookbook example: http://www.scipy.org/Cookbook/Matplotlib/Animations?action=show#head-3d51654b8306b1585664e7fe060a60fc76e5aa08 . Specifically, the example calls canvas.copy_from_bbox() before the initial draw(). This doesn’t throw an error, but will result in unexpected behavior (I spent an embarrassing amount of time debugging the resulting confusion in my own code).

The solution I came up with to fix the issue is to structure the code as follows:

…set up plot…
background = None

def animate(*args):
global background
if background is None:
background = canvas.copy_from_bbox(ax.bbox)

canvas.restore_region(background)
...rest of animation...

gobject.idle_add(animate)
p.show()

This works, but I dislike it for two reasons: I have to use a global variable, and there is an extra conditional test in every call to the animation function. Obviously neither flaw is terribly serious, but I was wondering if there is a better / accepted way of handling this. Or, am I just completely off-base on this whole issue – I’m new to matplotlib, still figuring things out.

Thanks,
Drew Frank

Drew,

What sort of unexpected behaviors occurred from calling .copy_from_background() before the initial draw and which backend were you using?

Also, if you are feeling adventurous, there is a very nice Animation module in the development branch of matplotlib that you might find handy. We are working on eliminating some of the older methods of doing animations and replacing them with a much cleaner interface. If you try it out, we greatly welcome any feedback on what you find useful/not useful about it.

Ben Root

···

On Tue, Oct 26, 2010 at 12:45 AM, Drew Frank <drewfrank@…985…> wrote:

I believe I’ve found a problem with the following cookbook example: http://www.scipy.org/Cookbook/Matplotlib/Animations?action=show#head-3d51654b8306b1585664e7fe060a60fc76e5aa08 . Specifically, the example calls canvas.copy_from_bbox() before the initial draw(). This doesn’t throw an error, but will result in unexpected behavior (I spent an embarrassing amount of time debugging the resulting confusion in my own code).

The solution I came up with to fix the issue is to structure the code as follows:

…set up plot…
background = None

def animate(*args):
global background
if background is None:
background = canvas.copy_from_bbox(ax.bbox)

canvas.restore_region(background)
...rest of animation...

gobject.idle_add(animate)
p.show()

This works, but I dislike it for two reasons: I have to use a global variable, and there is an extra conditional test in every call to the animation function. Obviously neither flaw is terribly serious, but I was wondering if there is a better / accepted way of handling this. Or, am I just completely off-base on this whole issue – I’m new to matplotlib, still figuring things out.

Thanks,
Drew Frank