【发布时间】:2017-03-26 12:58:47
【问题描述】:
我正在制作一个 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')
【问题讨论】:
-
您的设置是否可以用于透明图形补丁?您可以通过
matplotlib.rcParams['savefig.frameon']进行检查,它应该是True,以使每个新补丁都具有纯色背景(matplotlib.org/api/pyplot_api.html)或使用anim.save('anim.mp4', [..etc..], extra_args={'frameon':True})(matplotlib.org/api/animation_api.html)设置参数 -
选中此项以更改箭头的位置:stackoverflow.com/questions/17758942/…
-
按照@Jean 的建议使用 q.set_offsets 效果很好。谢谢!
标签: python animation matplotlib gif mp4