gpt4 book ai didi

python - Matplotlib FuncAnimation 只绘制一帧

转载 作者:太空宇宙 更新时间:2023-11-03 13:46:44 33 4
gpt4 key购买 nike

我正在尝试使用 FuncAnimation 模块制作动画,但我的代码只生成一帧然后停止。它似乎没有意识到它需要更新什么。你能帮我看看哪里出了问题吗?

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()

最佳答案

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()

你需要保留对动画对象的引用,否则它会被垃圾收集并且它的计时器会消失。

an open issue将动画的硬引用附加到底层 Figure 对象。

如所写,您的代码只绘制了一个不可见的点,我对其进行了一些更改以绘制当前索引

关于python - Matplotlib FuncAnimation 只绘制一帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18745391/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com