Search code examples
pythonmatplotlibanimation

Save matplotlib as mp4 in python


from matplotlib import pyplot as plt 
import numpy as np 
import matplotlib.animation as animation 
  
fig = plt.figure() 
axis = plt.axes(xlim=(0, 4),  ylim=(-1.5, 1.5)) 
line, = axis.plot([], [], lw=3) 
def animate(frame_number): 
    x = np.linspace(0, 4, 1000) 
    y = np.sin(2 * np.pi * (x - 0.01 * frame_number)) 
    line.set_data(x, y) 
    line.set_color('green') 
    return line, 

anim = animation.FuncAnimation(fig, animate, frames=100,  
                               interval=20, blit=True) 
fig.suptitle('Sine wave plot', fontsize=14) 
anim.save("animation.gif", dpi=300, writer=animation.PillowWriter(fps=25)) # works fine

anim.save("animation.mp4", writer = animation.FFMpegWriter(fps=25))# doesn't work

I can save the above plot as .gif without any problems.

But when I'm trying to save it as .mp4 I get the following error:

\AppData\Local\Programs\Python\Python312\Lib\site-packages\matplotlib\animation.py:240, in AbstractMovieWriter.saving(self, fig, outfile, dpi, *args, **kwargs)
...
   1553     self._close_pipe_fds(p2cread, p2cwrite,
   1554                          c2pread, c2pwrite,
   1555                          errread, errwrite)

FileNotFoundError: [WinError 2] The system cannot find the file specified

Solution

  • Current work around is to save a lot of images and animate it using "moviepy".

    from matplotlib import pyplot as plt 
    import numpy as np 
    import glob
    import moviepy.video.io.ImageSequenceClip
    
    image_folder = r"C:\Users\user\Desktop\save_images"
    
    for frame_number in range(100):
        x = np.linspace(0, 4, 1000) 
        y = np.sin(2 * np.pi * (x - 0.01 * frame_number)) 
        x = np.linspace(0, 4, 1000) 
        plt.plot(x,y)
        plt.savefig(fr"{image_folder}\{frame_number}.png")
        plt.close()
    
    image_files = glob.glob(fr'{image_folder}/*.png')
    
    fps = 1
    clip = moviepy.video.io.ImageSequenceClip.ImageSequenceClip(image_files, fps=fps)
    clip.write_videofile(fr'{image_folder}\my_new_video.mp4')