Python Matplotlib FuncAnimation only draws one fra

2019-01-15 20:16发布

Earthlings!
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 he 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()

1条回答
我命由我不由天
2楼-- · 2019-01-15 21:15
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

查看更多
登录 后发表回答