0
0
Matplotlibdata~30 mins

Saving animations (GIF, MP4) in Matplotlib - Mini Project: Build & Apply

Choose your learning style9 modes available
Saving animations (GIF, MP4)
📖 Scenario: You are creating a simple animated plot to show how a sine wave changes over time. You want to save this animation as both a GIF and an MP4 file so you can share it easily.
🎯 Goal: Build a Python script using matplotlib to create a sine wave animation and save it as a GIF and MP4 file.
📋 What You'll Learn
Create a time series data for the sine wave.
Set up the animation function using matplotlib.
Save the animation as a GIF file.
Save the animation as an MP4 file.
💡 Why This Matters
🌍 Real World
Animations help visualize changes over time in data, useful in science, engineering, and education.
💼 Career
Knowing how to create and save animations is valuable for data scientists and analysts who present dynamic data insights.
Progress0 / 4 steps
1
Create the sine wave data
Import numpy as np and matplotlib.pyplot as plt. Then create a numpy array called x with 100 points from 0 to 2π using np.linspace(0, 2 * np.pi, 100).
Matplotlib
Need a hint?

Use np.linspace to create evenly spaced points between 0 and 2π.

2
Set up the animation configuration
Create a figure and axis using plt.subplots() and assign them to variables fig and ax. Then create a line object using ax.plot with initial empty data and assign it to line.
Matplotlib
Need a hint?

Use ax.plot([], []) to create an empty line that will be updated in the animation.

3
Create the animation function
Import FuncAnimation from matplotlib.animation. Define a function called update that takes a frame number i and updates the line data to show y = np.sin(x + i / 10). Then create an animation object called ani using FuncAnimation with fig, update, and frames=100.
Matplotlib
Need a hint?

The update function changes the y-values of the line for each frame.

4
Save the animation as GIF and MP4
Save the animation ani as a GIF file named animation.gif using ani.save with writer='pillow'. Then save the same animation as an MP4 file named animation.mp4 using ani.save with writer='ffmpeg'. Finally, print 'Saved animation.gif and animation.mp4'.
Matplotlib
Need a hint?

Use ani.save('filename', writer='pillow') for GIF and ani.save('filename', writer='ffmpeg') for MP4.