Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib FuncAnimation only draws one frame

I am trying to do an animation using the FuncAnimation module, but my code only produces one frame and then stops. It seems like it doesn't realize what it needs to update. Can you help me what went wrong?

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

x = np.linspace(0,2*np.pi,100)

def animate(i):
    PLOT.set_data(x[i], np.sin(x[i]))
    print("test")
    return PLOT,

fig = plt.figure()  
sub = fig.add_subplot(111, xlim=(x[0], x[-1]), ylim=(-1, 1))
PLOT, = sub.plot([],[])

animation.FuncAnimation(fig, animate, frames=len(x), interval=10, blit=True)
plt.show()
like image 754
throwaway17434 Avatar asked Sep 11 '13 15:09

throwaway17434


1 Answers

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

x = np.linspace(0,2*np.pi,100)

fig = plt.figure()  
sub = fig.add_subplot(111, xlim=(x[0], x[-1]), ylim=(-1, 1))
PLOT, = sub.plot([],[])

def animate(i):
    PLOT.set_data(x[:i], np.sin(x[:i]))
    # print("test")
    return PLOT,

ani = animation.FuncAnimation(fig, animate, frames=len(x), interval=10, blit=True)
plt.show()

You need to keep a reference to the animation object around, otherwise it gets garbage collected and it's timer goes away.

There is an open issue to attach a hard-ref to the animation to the underlying Figure object.

As written, your code well only plot a single point which won't be visible, I changed it a bit to draw up to current index

like image 113
tacaswell Avatar answered Nov 11 '22 11:11

tacaswell