本文介绍了matplotlib将动画保存为gif错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将matplotlib动画保存为gif格式.
I want to save matplotlib animation in gif format.
我成功使用代码将动画保存为mp4格式
I succeded to save animation to mp4 format, using code
import matplotlib
matplotlib.use("Agg")
~some codes~
ani = animation.FuncAnimation(fig, draw, update, interval=10, blit=False)
mywriter = animation.FFMpegWriter(fps=60)
ani.save('myanimation.mp4',writer=mywriter)
但是如果我将myanimation.mp4更改为gif格式,则python会出错
but if I change myanimation.mp4 to gif format, python makes error
Traceback (most recent call last):
File "C:\Users\Administrator\Desktop\edison\Edison_v4_backup_1\ver5.py", line 164, in <module>
ani.save('demoanimation.gif',writer=mywriter);
File "C:\Python27\lib\site-packages\matplotlib\animation.py", line 718, in save
writer.grab_frame(**savefig_kwargs)
File "C:\Python27\lib\site-packages\matplotlib\animation.py", line 204, in grab_frame
dpi=self.dpi, **savefig_kwargs)
File "C:\Python27\lib\site-packages\matplotlib\figure.py", line 1421, in savefig
self.canvas.print_figure(*args, **kwargs)
File "C:\Python27\lib\site-packages\matplotlib\backend_bases.py", line 2220, in print_figure
**kwargs)
File "C:\Python27\lib\site-packages\matplotlib\backends\backend_agg.py", line 497, in print_raw
renderer._renderer.write_rgba(filename_or_obj)
RuntimeError: Error writing to file
看到我成功保存为mp4格式,我不知道为什么保存gif格式时会出错.
Seeing that I succeded to save in mp4 format, I don't know why it makes error when saving gif format.
推荐答案
这是因为matplotlib
在没有外部程序的情况下不支持GIF.如果您已经正确安装和配置了imagemagick
,它将可以正常工作:
This is because matplotlib
does not support GIFs without external programs. If you have imagemagick
correctly installed and configured, this should work:
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.animation
import numpy as np
def init_animation():
global line
line, = ax.plot(x, np.zeros_like(x))
ax.set_xlim(0, 2*np.pi)
ax.set_ylim(-1,1)
def animate(i):
line.set_ydata(np.sin(2*np.pi*i / 50)*np.sin(x))
return line,
fig = plt.figure()
ax = fig.add_subplot(111)
x = np.linspace(0, 2*np.pi, 200)
ani = matplotlib.animation.FuncAnimation(fig, animate, init_func=init_animation, frames=50)
ani.save('/tmp/animation.gif', writer='imagemagick', fps=30)
这篇关于matplotlib将动画保存为gif错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!