matplotlib save animation in gif error

后端 未结 5 705
时光取名叫无心
时光取名叫无心 2020-11-29 08:58

I want to save matplotlib animation in gif format.

I succeded to save animation to mp4 format, using code

import matplotlib
matplotlib.use(\"Agg\")

         


        
5条回答
  •  再見小時候
    2020-11-29 09:17

    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

提交回复
热议问题