如何覆盖动画方法?matplotlib.animation.FuncAnimation

2024-05-20 01:32:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我想把一些额外的参数交给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,
)

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


1条回答
网友
1楼 · 发布于 2024-05-20 01:32:11

下面是一个如何将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')

哪些输出:
Animated gif

相关问题 更多 >