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

fig = plt.figure()
ax = fig.add_subplot(111)

x = np.arange(0, 2*np.pi, 0.01)        # x-array
i=1
line, = ax.plot(x, np.sin(x))

def animate():
    i= i+2
    x=x[1:] + [i]
    line.set_ydata(np.sin(x))  # update the data
    return line,

#Init only required for blitting to give a clean slate.
def init():
    line.set_ydata(np.ma.array(x, mask=True))
    return line,

ani = animation.FuncAnimation(fig, animate, init_func=init,
    interval=25, blit=True)
plt.show()

我收到这样的错误:animate() 不接受任何参数(给定 1 个)......所以很困惑。我什至不给回调函数一个参数。有什么我错过的吗?

谢谢。

4

1 回答 1

6

看起来文档已经关闭,或者至少在这里不清楚:该函数有一个内在的第一个参数,即帧号。因此,您可以简单地将其定义为def animate(*args)or def animate(framenumber, *args),甚至def animate(framenumber, *args, **kwargs)

另请参阅此示例

请注意,之后您会遇到其他问题:

  • ixinsideanimate应该被声明global。或者更好的是,通过fargs关键字 in将它们作为参数传递FuncAnimation

  • x = x[1:] + [i]不像你想象的那样工作。Numpy 数组的工作方式与列表不同:它会添加[i]到 的每个元素x[1:]并将其分配给x,从而使x一个元素更短。一种可能的正确方法是x[:-1] = x[1:]; x[-1] = i.

于 2012-11-30T10:02:11.230 回答