FuncAnimation():删除/更新旧行

时间:2015-11-19 08:53:45

标签: python matplotlib

在这里,我的代码被剥离到最小,以正确地重现我的问题。

push, pull, clone and log

问题是我想要新的垂直线(以不同的能量)来替换旧线。相反,最后一帧显示所有行。

我发现了一个类似的问题(matplotlib circle, animation, how to remove old circle in animation),但似乎并不适用于我的情况。

即使import matplotlib.animation as animation import os import matplotlib.pyplot as plt import numpy as np import os.path f, ((ax1, ax2)) = plt.subplots(1, 2, figsize=(20,10)) def animate(i): chosenEnergy = (0.0 + (i-1)*(0.02)) chosenEnergyLine = ax2.axvline(float(chosenEnergy),0,1, linestyle='dashed') return chosenEnergyLine, def init(): chosenEnergyLine = ax2.axvline(0.0,0,1, linestyle='dashed') return chosenEnergyLine, ani = animation.FuncAnimation(f, animate, np.arange(1,nE), init_func=init, interval=25, blit=False, repeat = False) plt.rcParams['animation.ffmpeg_path'] = '/opt/local/bin/ffmpeg' FFwriter = animation.FFMpegWriter() ani.save('basic_animation.mp4', writer = FFwriter, fps=30, extra_args=['-vcodec', 'libx264']) print "finished" 存在与此类似问题(set_radius)的答案中使用的功能类似的功能,我也不愿意使用它。在我的另一个子图(ax1)中,我有一个散点图,每次都要更新。是否有一般方法在下一个时间步之前清除情节?

使用blit = False或blit = True时,我也没有发现任何变化。

有关如何进行的任何建议吗?

1 个答案:

答案 0 :(得分:1)

每次拨打animate时,您都会画一条新线。您应该删除旧行,或使用set_xdata移动您的行,而不是绘制新行。

def animate(i,chosenEnergyLine):
    chosenEnergy = (0.0 + (i-1)*(0.02))
    chosenEnergyLine.set_xdata([chosenEnergy, chosenEnergy])
    return chosenEnergyLine,

chosenEnergyLine = ax2.axvline(0.0,0,1, linestyle='dashed')
ani = animation.FuncAnimation(f, animate, np.arange(1,10),
       fargs=(chosenEnergyLine,), interval=25, blit=False, repeat = False)

更新:这是因为您尝试多次删除相同的全局chosenEnergyLineFuncAnimation捕获animate的返回值,但它不会用它更新全局chosenEnergyLine。解决方案是在动画中使用一种静态变量来跟踪最新的chosenEnergyLine

def animate(i):
    chosenEnergy = (0.0 + (i-1)*(0.02))
    animate.chosenEnergyLine.remove()
    animate.chosenEnergyLine = ax2.axvline(float(chosenEnergy),0,1, linestyle='dashed')
    return animate.chosenEnergyLine,

animate.chosenEnergyLine = ax2.axvline(0.0,0,1, linestyle='dashed')

ani = animation.FuncAnimation(f, animate, np.arange(1,10),
                interval=25, blit=False, repeat = False)