Course contentsShow
← Data Science
Lesson 1328 of 2,14533. Advanced Visualization TechniquesFree lesson

Saving and Embedding Animations

Exporting animations as GIF or MP4 files and embedding them in Jupyter notebooks or web applications.

Saving and Embedding Animations

What you'll learn: How to export your animated visualizations as video files and display them in notebooks or web applications.

Once you've created an animation using FuncAnimation, you'll want to save it for sharing or embed it directly in your Jupyter notebook. This step transforms your dynamic visualization from a temporary display into a portable, shareable asset.

Exporting Animations

Think of saving an animation like converting a live theater performance into a movie—you're capturing the dynamic content in a file format others can watch anywhere.

To save an animation, use the .save() method on your FuncAnimation object:

from matplotlib.animation import FuncAnimation
import matplotlib.pyplot as plt

# Assume you've created an animation called 'ani'
ani.save('my_animation.gif', writer='pillow', fps=30)

For MP4 format (requires FFmpeg installed):

ani.save('my_animation.mp4', writer='ffmpeg', fps=30, dpi=100)

The writer parameter specifies the encoding library, fps controls frame rate (smoothness), and dpi affects resolution.

Embedding in Jupyter Notebooks

To display animations directly in Jupyter without creating files, use:

from IPython.display import HTML
HTML(ani.to_html5_video())

This converts your animation to an HTML5 video that plays inline, perfect for interactive notebooks and presentations.

For web applications, save as GIF or MP4 and reference the file path in your HTML <img> or <video> tags.

Key Takeaway: Save animations with .save() using writers like 'pillow' (GIF) or 'ffmpeg' (MP4), and embed them in Jupyter notebooks using HTML(ani.to_html5_video()) for seamless inline playback.