如何重置 matplotlib 动画而不重新运行脚本

Dan*_* Lo 7 python animation matplotlib figure

我正在使用 matplotlib 的 FuncAnimation 函数对大型数据集的一部分进行动画处理:

fig = plt.figure(figsize=(15, 11.5))
ax = fig.add_subplot(111, aspect='equal', autoscale_on=False,
                     xlim=(x1,x2), ylim=(y1, y2))

data,=ax.plot([],[],'o')

def init():
    data.set_data([],[])
    return data


def animate(t):
    global x_pos,y_pos
    data.set_data(x_pos[t],y_pos[t])
    return data

ani=animation.FuncAnimation(fig,animate,frames=duration,interval=20,
                            init_func=init,blit=True)


plt.show()
Run Code Online (Sandbox Code Playgroud)

当我从头开始运行代码时,效果很好。但是,由于这涉及加载和预处理大型数据集,因此需要几分钟的时间,因此我希望能够仅运行一段代码来测试和制作动画。

然而,当我关闭动画并尝试再次运行它时,我只剩下一个空白图形 - 没有绘制任何点,并且永远不会调用 animate() 函数(我使用 print 语句对此进行了测试)。

我尝试清除情节和图形:

plt.clf()
fig.close()
plt.clear(figure)
Run Code Online (Sandbox Code Playgroud)

并尝试不同的数字,但结果是相同的。

如何清除动画以便可以再次运行它而无需重新运行整个脚本?

Ben*_*Ben 0

尝试这个:

ani.frame_seq = ani.new_frame_seq() 
Run Code Online (Sandbox Code Playgroud)