Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to animate a line plot in Matplotlib?
Animating line plots in Matplotlib allows you to create dynamic visualizations that show data changes over time. The animation.FuncAnimation class provides an easy way to create smooth animations by repeatedly updating plot data.
Basic Animation Setup
To create an animated line plot, you need to set up the figure, define an update function, and use FuncAnimation to handle the animation loop ?
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
# Set up the figure and axis
fig, ax = plt.subplots()
ax.set_xlim(-3, 3)
ax.set_ylim(-1, 1)
ax.set_title('Animated Sine Wave')
# Create data
x = np.linspace(-3, 3, 91)
t = np.linspace(1, 25, 30)
X2, T2 = np.meshgrid(x, t)
sinT2 = np.sin(2 * np.pi * T2 / T2.max())
F = 0.9 * sinT2 * np.sinc(X2 * (1 + sinT2))
# Initialize the line plot
line, = ax.plot(x, F[0, :], color='blue', linewidth=2)
# Animation function
def animate(frame):
line.set_ydata(F[frame, :])
return line,
# Create animation
anim = animation.FuncAnimation(fig, animate, frames=len(t)-1,
interval=100, blit=True, repeat=True)
plt.show()
Key Components Explained
Data Preparation
The animation uses a 2D array where each row represents the y-values for one frame ?
import numpy as np
# Create x coordinates (fixed for all frames)
x = np.linspace(0, 4*np.pi, 100)
# Create time points for animation frames
time_points = np.linspace(0, 2*np.pi, 50)
# Generate y-data for each frame
frames_data = []
for t in time_points:
y = np.sin(x + t)
frames_data.append(y)
print(f"Created {len(frames_data)} frames")
print(f"Each frame has {len(frames_data[0])} data points")
Created 50 frames Each frame has 100 data points
Animation Function
The animate function updates the plot data for each frame ?
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
# Simple moving sine wave
fig, ax = plt.subplots()
x = np.linspace(0, 4*np.pi, 100)
line, = ax.plot(x, np.sin(x))
ax.set_ylim(-1.5, 1.5)
ax.set_title('Moving Sine Wave')
def animate(frame):
# Update y-data with phase shift
y = np.sin(x + frame * 0.1)
line.set_ydata(y)
return line,
# Create animation with 200 frames
anim = animation.FuncAnimation(fig, animate, frames=200,
interval=50, blit=True)
plt.show()
Animation Parameters
| Parameter | Description | Example Value |
|---|---|---|
frames |
Number of animation frames | 100 |
interval |
Delay between frames (ms) | 50 |
blit |
Optimize drawing for speed | True |
repeat |
Loop animation continuously | True |
Saving Animations
You can save animations as GIF or MP4 files ?
# Save as GIF (requires pillow)
anim.save('animation.gif', writer='pillow', fps=20)
# Save as MP4 (requires ffmpeg)
anim.save('animation.mp4', writer='ffmpeg', fps=30)
Conclusion
Matplotlib's FuncAnimation makes it easy to create animated line plots by repeatedly calling an update function. Use blit=True for better performance and adjust interval to control animation speed.
