matplotlib imshow(): how to animate?

You’re very close, but there’s one mistake – init and animate should return iterables containing the artists that are being animated. That’s why in Jake’s version they return line, (which is actually a tuple) rather than line (which is a single line object). Sadly the docs are not clear on this!

You can fix your version like this:

# initialization function: plot the background of each frame
def init():
    im.set_data(np.random.random((5,5)))
    return [im]

# animation function.  This is called sequentially
def animate(i):
    a=im.get_array()
    a=a*np.exp(-0.001*i)    # exponential decay of the values
    im.set_array(a)
    return [im]

Leave a Comment