Python FuncAnimation():删除/更新旧行
在这里,我的代码被剥离到最底层,以正确地再现我的问题Python FuncAnimation():删除/更新旧行,python,matplotlib,Python,Matplotlib,在这里,我的代码被剥离到最底层,以正确地再现我的问题 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
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"
问题是,我想用新的垂直线(以不同的能量)来代替旧的线。相反,最后一帧显示所有线
我发现了一个类似的问题(),但似乎不适用于我的情况
即使对于xvline
,存在与此类似问题的答案(set\u radius
)中使用的函数类似的函数,我还是不想使用它。在我的另一个子图(ax1)中,我有一个散点图,每次都必须更新。在下一个时间步骤之前,是否有一个清除绘图的常规方法
当使用blit=False或blit=True时,我也没有注意到任何变化
有关于如何继续的建议吗?每次调用
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中使用某种静态变量来跟踪最新的chosenergyline
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)
我懂了。谢谢还有你的其他建议呢:删除旧线条(或散点图等)?这对我来说可能更一般、更有用,因为我的图形中还有其他部分需要在每一步更新。。。我尝试在
动画部分中使用del
或obj.remove()函数,但无法使其工作。通常,它会抱怨chosenEnergyLine
对象不存在。工作起来像个符咒。谢谢@Azad如果我们有多条线,但只有在处理下一个数据点时才能知道质量,会发生什么?