Saving animations lets you share or reuse your moving charts outside Python. GIFs and MP4s are common formats to show animations easily.
0
0
Saving animations (GIF, MP4) in Matplotlib
Introduction
You want to show a changing trend in data as a video or looping image.
You need to include an animation in a presentation or report.
You want to share your animated plot on social media or websites.
You want to save your animation for later review or comparison.
Syntax
Matplotlib
anim.save('filename.format', writer='writer_name', fps=frames_per_second)
anim is your animation object created by FuncAnimation or similar.
filename.format is the output file name with extension like .gif or .mp4.
Examples
Saves the animation as a GIF using the Pillow writer at 10 frames per second.
Matplotlib
anim.save('animation.gif', writer='pillow', fps=10)
Saves the animation as an MP4 video using FFmpeg at 30 frames per second.
Matplotlib
anim.save('animation.mp4', writer='ffmpeg', fps=30)
Sample Program
This code creates a simple sine wave animation that moves over time. It saves the animation as both a GIF and an MP4 file using appropriate writers.
Matplotlib
import numpy as np import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation x = np.linspace(0, 2 * np.pi, 200) y = np.sin(x) fig, ax = plt.subplots() line, = ax.plot(x, y) # Function to update the frame def update(frame): line.set_ydata(np.sin(x + frame / 10)) return line, anim = FuncAnimation(fig, update, frames=100, interval=50) # Save as GIF anim.save('sine_wave.gif', writer='pillow', fps=20) # Save as MP4 anim.save('sine_wave.mp4', writer='ffmpeg', fps=20) plt.close(fig) # Close plot to avoid displaying in some environments print('Animations saved as sine_wave.gif and sine_wave.mp4')
OutputSuccess
Important Notes
To save MP4 files, you need FFmpeg installed on your system and accessible in your PATH.
For GIFs, the Pillow library is used as the writer, which is usually installed with matplotlib.
Adjust fps (frames per second) to control animation speed and file size.
Summary
Use anim.save() to save animations as GIF or MP4 files.
Choose the writer: 'pillow' for GIF, 'ffmpeg' for MP4.
Make sure required tools like FFmpeg are installed for video saving.