【问题标题】:Previous frames not cleared when saving matplotlib animation保存 matplotlib 动画时未清除前一帧
【发布时间】: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')

【问题讨论】:

标签: python animation matplotlib gif mp4


【解决方案1】:

解决方案位于here,正如上面 Jean-Sébastien 所建议的那样。我的代码现在是:

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')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-16
    • 2020-07-12
    • 2014-07-14
    相关资源
    最近更新 更多