将动画 Matplotlib 图表保存为 GIF

Saving Animated Matplotlib Chart to GIF

我有一个动画 matplotlib 图表,我正在尝试将其保存到 .gif 文件,但我的图像编写器无法工作。

我已经安装了 imagemagick 并通过 installation page 上给出的说明验证了它在我的计算机上工作,但是当我这样做时:

anim.save('gd.gif', writer='imagemagick')

我收到以下错误消息:

MovieWriter imagemagick unavailable. Trying to use pillow instead.

但是,执行 anim.save('gd.gif', writer='pillow') 会给出以下错误消息:

ValueError: not enough image data

我尝试使用命令 conda install -c conda-forge ffmpeg 安装 ffmpeg。看起来它安装正确,但我显然不知道如何将它绑定到 matplotlib。

将编写器指定为 ffmpeg 会给出与我在 imagemagick 中遇到的相同的错误消息。

我还尝试使用以下行将 imagemagick 的路径添加到 matplotlib 的配置文件路径:

animation.convert_path: 'C:\Program Files\ImageMagick-7.0.8-Q16\magick.exe'

那是 suggested in this question

None 这些似乎都奏效了。

我在 Windows 10,我正在使用 Python 3.7

我从互联网上截取了这段代码,最初没有用。
我更改了行:

rcParams['animation.convert_path'] = r'/usr/bin/convert'

指向我的 convert 二进制文件,它启动了。 不可否认,这是在 Linux 上,但我认为它应该没有什么不同。 正如 Mark Setchell 在对原始问题的评论中指出的那样, binary 的名称似乎很可能取决于您使用的 version/operating 系统。要隔离使用哪个,我建议先在 command line 上尝试命令。
例如对我来说 Linux:

convert -version

给出:

Version: ImageMagick 6.9.7-4 Q16 x86_64 20170114 http://www.imagemagick.org

您的里程可能会有所不同!特别是当我不再记得在 Windows OS.

上发出终端命令时
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import rcParams

# configure full path for ImageMagick
rcParams['animation.convert_path'] = r'/usr/bin/convert'

TWOPI = 2*np.pi

fig, ax = plt.subplots()

t = np.arange(0.0, TWOPI, 0.001)
s = np.sin(t)
l = plt.plot(t, s)

ax = plt.axis([0,TWOPI,-1,1])

redDot, = plt.plot([0], [np.sin(0)], 'ro')

def animate(i):
    redDot.set_data(i, np.sin(i))
    return redDot,

# create animation using the animate() function with no repeat
myAnimation = animation.FuncAnimation(fig, animate, frames=np.arange(0.0, TWOPI, 0.1), \
                                      interval=10, blit=True, repeat=False)

# save animation at 30 frames per second
myAnimation.save('myAnimation.gif', writer='imagemagick', fps=30)

一个快速的解决方法是在 运行 anim.save('gd.gif', writer='imagemagick') 之前添加 plt.show()。当您关闭绘图时,它会正确保存动画。