如何移除/更新旧的动画线
这是我简化后的代码,目的是为了准确地重现我的问题。
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"
我的问题是,我想用一条新的竖线(在不同的能量位置)来替换旧的竖线。但最终的画面却显示了所有的竖线。
我找到一个类似的问题(matplotlib 圆形动画,如何在动画中移除旧圆),但似乎不适用于我的情况。
即使有一个类似于这个类似问题答案中提到的函数(set_radius
)可以用在xvline
上,我也不想使用它。在我的另一个子图(ax1)中,有一个散点图,每次都需要更新。有没有什么通用的方法可以在下一个时间步骤之前清空图表?
我也没有注意到使用blit=False或blit=True时有什么变化。
有什么建议可以让我继续吗?
相关文章:
- 暂无相关问题
1 个回答
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)
更新:这是因为你试图多次删除同一个全局变量 chosenEnergyLine
(FuncAnimation
捕捉到 animate
的返回值,但并不会用这个值更新全局的 chosenEnergyLine
)。解决办法是在 animate
中使用一种静态变量来跟踪最新的 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)