Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
798 views
in Technique[技术] by (71.8m points)

matplotlib save animation in gif error

I want to save matplotlib animation in gif format.

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)

but if I change myanimation.mp4 to gif format, python makes error

Traceback (most recent call last):
  File "C:UsersAdministratorDesktopedisonEdison_v4_backup_1ver5.py", line 164, in <module>
    ani.save('demoanimation.gif',writer=mywriter);
  File "C:Python27libsite-packagesmatplotlibanimation.py", line 718, in save
    writer.grab_frame(**savefig_kwargs)
  File "C:Python27libsite-packagesmatplotlibanimation.py", line 204, in grab_frame
    dpi=self.dpi, **savefig_kwargs)
  File "C:Python27libsite-packagesmatplotlibfigure.py", line 1421, in savefig
    self.canvas.print_figure(*args, **kwargs)
  File "C:Python27libsite-packagesmatplotlibackend_bases.py", line 2220, in print_figure
    **kwargs)
  File "C:Python27libsite-packagesmatplotlibackendsackend_agg.py", line 497, in print_raw
    renderer._renderer.write_rgba(filename_or_obj)
RuntimeError: Error writing to file

Seeing that I succeded to save in mp4 format, I don't know why it makes error when saving gif format.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...