How to save animations as mp4 videos and animated GIFs

Finally, to write these animations instead of having them displayed in the Jupyter Notebook, we need to produce a video or an animated GIF that we can put into a PowerPoint presentation or on a website. To do this, we simply take the return value of the animation and use the save method. Hence, by using anim.save, we can produce sine.mp4, which will take some time to render:

# Saving the animation as a mp4 video
nums = np.arange(0,10,0.1)
sin, = plt.plot(nums, np.sin(nums))
frames=np.arange(0,2*np.pi,0.1)
def update(i):
sin.set_ydata(np.sin(nums+i))
anim = FuncAnimation(plt.gcf(), update, frames=frames, interval=50)
anim.save('sine.mp4')

Use the VLC player to play the video that we have produced (!vlc sine.mp4). By using VLC on sine.mp4, we get an mp4 video, which automatically produces the requisite output.

To produce an animated .gif, we need to pass in the writer argument to specify what will write this out. We will use an argument called ImageMagick, which is a commonly used toolkit on most systems. By running !eog sine.gif, we get an animated .gif.

By using these animation toolkits that Matplotlib provides, it is actually quite easy to produce movies and animations in Matplotlib. A couple of years ago, that wasn't the case, but this toolkit has matured quite significantly in the last few years.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset