matplotlib动画函数需要一个参数,不需要

时间:2019-02-16 16:16:23

标签: python-3.x matplotlib animation

import numpy as np
from matplotlib import pyplot as plt
from matplotlib.animation import FuncAnimation


fig, ax = plt.subplots()


def animate(t):

    x = np.random.normal(0,1,[1000,1])
    y = np.random.normal(0,1,[1000,10])    



    for i,v in enumerate(range(y.shape[1])):
        op = x
        hop = y[:,[i]]
    ax.clear()
    ax.scatter(op,hop)



ani = FuncAnimation(fig,animate,interval=1000)
plt.show()

通知函数animate()的参数为t> animate(t)。我真的不明白为什么,因为t并不代表任何意义,它不依赖于代码中的任何事物。为什么这是必要的?如果我创建一个不带参数的函数> animate()并运行代码,则会出现此错误:

TypeError: animate() takes 0 positional arguments but 1 was given

我很困惑为什么需要这个t。它只是没有任何意义,它不会传递任何信息。

1 个答案:

答案 0 :(得分:2)

阅读FuncAnimation documentation

FuncAnimation(fig, func, frames=None, ...)
  

func:可调用   在每一帧调用的函数。 第一个参数将是frames 中的下一个值。可以通过fargs参数提供任何其他位置参数。

     

[...]

     

frames:可迭代,整数,生成器函数或无,可选   传递func和动画每一帧的数据源

     

如果是可迭代的,则只需使用提供的值即可。如果iterable有长度,它将覆盖save_count kwarg。

     

如果是整数,则等于通过范围(帧)

     

如果是生成器函数,则必须具有签名:

   def gen_function() -> obj
     

如果为None,则等同于传递itertools.count

(强调我的)

因此,动画功能需要采用一个参数,该参数由设置为frames的任何参数生成。如果frames = None就像您不提供该参数的情况一样,它将只是整数,从0开始,一直计数直到停止动画。

要查看实际的参数,请尝试类似

def animate(t):
    print(t)

ani = FuncAnimation(fig,animate,interval=1000)
plt.show()

def animate(t):
    print(t)

ani = FuncAnimation(fig,animate,frames=[23,56,129], interval=1000)
plt.show()

关于问题中的代码,我不确定应该实现什么,但是我想您宁愿在y的列上执行动画。

import numpy as np
from matplotlib import pyplot as plt
from matplotlib.animation import FuncAnimation

fig, ax = plt.subplots()

x = np.random.normal(0,1,[1000,1])
y = np.random.normal(0,1,[1000,10])    

def animate(t):
    ax.clear()
    ax.scatter(x,y[:,t])

ani = FuncAnimation(fig, animate, frames=10, interval=1000)
plt.show()
相关问题