Matplotlib 无法保存动画

Matplotlib can not save animation

我有一个matplotlib动画,它不会保存。如果我不保存它,它运行得很好并且没有错误。当我尝试用一​​条无用的消息保存它时出错。我用谷歌搜索了这个错误并检查了所有内容,但我似乎找不到这个问题的答案。我已经安装了 ffmpeg。我做错了什么很明显吗?如果重要的话,我 运行 在 ubuntu 19.10 上使用 matplotlib 3.2.1。

保存动画的代码如下:

    def run_animation(self, total_rounds):
        anim = animation.FuncAnimation(self.fig, self.animate,
                                       init_func=self.init,
                                       frames=total_rounds * 100,
                                       interval=40,
                                       blit=True)
#        Writer = animation.writers['ffmpeg']
#        writer = Writer(fps=15, metadata=dict(artist='Me'), bitrate=1800)
        anim.save('animation.mp4')

错误回溯:

2020-04-01 02:20:58,279-INFO: MovieWriter._run: running command: ffmpeg -f rawvideo -vcodec rawvideo -s 1200x500 -pix_fmt rgba -r 25.0 -loglevel error -i pipe: -vcodec h264 -pix_fmt yuv420p -y animation.mp4
Traceback (most recent call last):
  File "/home/anon/.local/lib/python3.7/site-packages/matplotlib/backend_bases.py", line 2785, in _wait_cursor_for_draw_cm
    self.set_cursor(cursors.WAIT)
  File "/home/anon/.local/lib/python3.7/site-packages/matplotlib/backends/backend_gtk3.py", line 468, in set_cursor
    self.canvas.get_property("window").set_cursor(cursord[cursor])
AttributeError: 'NoneType' object has no attribute 'set_cursor'

感谢您的帮助

我想通了,奇怪的是我需要在所有导入语句之前执行此操作。

import matplotlib
matplotlib.use("Agg")

如果我没有那个,它就不会工作。另外,ffmpeg 开始需要一段时间,所以我修改了保存功能,如下所示:

anim.save('animation.mp4', progress_callback=lambda i, n: print(f'Saving frame {i} of {n}'))

文档中的一个不错的隐藏功能。希望没有其他人遇到这个问题!