关于matplotlib.animation.FuncAnimation的args

Don*_*Don 3 python animation matplotlib

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()
Run Code Online (Sandbox Code Playgroud)

我得到这样的错误:animate()不接受任何参数(给定1个)......很困惑.我甚至没有给回调函数一个arg.有没有我错过的东西?

谢谢.

小智 6

看起来文档已关闭,或者至少在此处不清楚:函数具有内在的第一个参数,即帧编号.所以,你可以简单地将其定义为def animate(*args)def animate(framenumber, *args),甚至def animate(framenumber, *args, **kwargs).

另请参见此示例.

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

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

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