Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
930 views
in Technique[技术] by (71.8m points)

python - 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()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...