Skip to main content
 首页 » 编程设计

python之保存 matplotlib 动画时未清除前一帧

2025年04月02日9tuyile006

我正在制作一个 matplotlib 动画,其中一个箭袋箭头在页面上移动。这不能以通常的方式实现(创建一个 Quiver 对象并用动画的每一帧更新它),因为虽然有一个 set_UVC 方法来更新 u, v 组件,没有用于更改箭头的 x、y 位置 的等效方法。因此,我正在为每一帧创建一个新的 Quiver 对象。

当我执行 plt.show() 并且在屏幕上绘制动画时,这很好用。箭头在页面上从左向右移动,当一个箭头出现时,前一个箭头消失,这就是我想要的。但是,当我保存为 gif 或 mp4 时,之前的箭头没有被清除,所以我最终出现了一整行箭头。我该如何解决这个问题?

我的代码如下:

import numpy as np 
import matplotlib.pyplot as plt 
import matplotlib.animation 
 
n = 21 
x = np.linspace(-1.0, 1.0, num=n) 
def animate(i): 
    q = plt.quiver(x[i:i+1], [0], [1], [0]) 
    return q, 
 
plt.gca().set_xlim([-1, 1]) 
anim = matplotlib.animation.FuncAnimation(plt.gcf(), animate, frames=n, 
                                          repeat=True, blit=True) 
 
plt.show() 
#anim.save('anim.gif', dpi=80, writer='imagemagick') 
#anim.save('anim.mp4', dpi=80, writer='ffmpeg') 

请您参考如下方法:

找到解决方案here ,正如上面让-塞巴斯蒂安所建议的那样。我的代码现在是:

import numpy as np 
import matplotlib.pyplot as plt 
import matplotlib.animation 
 
n = 21 
x = np.linspace(-1.0, 1.0, num=n) 
q = plt.quiver(x[:1], [0], [1], [0]) 
def animate(i): 
    q.set_offsets([[x[i], 0]]) 
    return q, 
 
plt.gca().set_xlim([-1, 1]) 
anim = matplotlib.animation.FuncAnimation(plt.gcf(), animate, frames=n, 
                                          repeat=True, blit=True) 
 
plt.show() 
#anim.save('anim.gif', dpi=80, writer='imagemagick') 
#anim.save('anim.mp4', dpi=80, writer='ffmpeg')