【问题标题】:How to overwrite animate method? matplotlib.animation.FuncAnimation如何覆盖动画方法? matplotlib.animation.FuncAnimation
【发布时间】:2021-07-30 12:27:45
【问题描述】:

我想为 animate_all 函数提供一些额外的参数。因此,我写了这样的新方法:

def animate_all(index, *fargs):
    print(index)
    all_positions_list = fargs[0]
    vel_list = fargs[1]

    return something

但是,我在调用该方法时遇到了问题。以下尝试均无效。

animation_1 = animation.FuncAnimation(
    fig,
    animate_all(70, all_positions_list, vel_list),
    interval=200,
    frames=70,
    cache_frame_data=False,
)

animation_1 = animation.FuncAnimation(
    fig,
    animate_all(all_positions_list, vel_list),
    interval=200,
    frames=70,
    cache_frame_data=False,
)

帧通常会“自动”传递,但如果我扩展了该功能,则不会。有人有解决办法吗?

【问题讨论】:

  • 您似乎没有正确调用FuncAnimation。您正在传递被调用的animate_all(...) 函数,而您应该只将animate_all 和fargs 传递给fargs=。看看examples in the docs
  • 我阅读了示例文档,但他们建议先计算所有内容,然后对其进行全局引用。在我看来,全局引用不是一个好的样式,所以我仍然想将额外的信息交给 animate_all()。这在文档中没有解释是吗?
  • 在文档中,如果您不想拥有全局图形,他们建议使用类。您不必预先计算数据,您可以使用生成器函数迭代地提供数据。

标签: python matplotlib animation


【解决方案1】:

这是一个示例,说明如何将fargs 与动画功能结合使用。

import matplotlib.pyplot as plt
import matplotlib.animation as animation

def animate(x_data, *args):
    y_data = x_data ** 2
    colour, style = args
    x.append(x_data)
    y.append(y_data)
    line.set_data(x, y)
    line.set(color=colour, linestyle=style)
    return line,
    
N = 21
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(3, 3))
x, y = [], []
ax.set_xlim(0, N)
ax.set_ylim(0, N ** 2)
line, = ax.plot([], [])

anim = animation.FuncAnimation(
    fig=fig, 
    func=animate, 
    frames=N,
    fargs=("red", "--"),
)
anim.save('anim.gif')

哪些输出:

【讨论】:

    猜你喜欢
    • 2016-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多