【问题标题】:matplotlib animation function wants an argument, which is not neededmatplotlib 动画函数需要一个不需要的参数
【发布时间】:2019-02-16 16:16:22
【问题描述】:
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。它只是没有任何意义,它不传递任何信息。

【问题讨论】:

  • 在 matplotlib 2.2.2 中对我来说很好
  • @Bazingaa 它运行时没有在动画函数中传递参数 t?
  • 是的,它在 jupyter notebook 中对我来说是这样运行的。我使用了from IPython.display import HTML,然后是HTML(ani.to_html5_video())。生成动画散布动画

标签: python-3.x matplotlib animation


【解决方案1】:

阅读FuncAnimation documentation

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

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

[...]

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

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

如果是整数,则等价于传递range(frames)

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

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

【讨论】:

  • 是的,你说的很对。还没有想出在函数内打印(t)的想法。现在我明白了。我感谢您的帮助。谢谢。
猜你喜欢
  • 2012-06-25
  • 2017-09-27
  • 2012-11-10
  • 2016-03-31
  • 1970-01-01
  • 1970-01-01
  • 2018-08-30
  • 1970-01-01
  • 2019-12-14
相关资源
最近更新 更多