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
Selected Reading
How to use matplotlib.animate to animate a contour plot in Python?
To animate a contour plot in matplotlib, we use FuncAnimation to repeatedly update the plot with new data frames. This creates smooth transitions between different contour patterns over time.
Steps to Create Animated Contour Plot
- Create multi-dimensional data with time frames
- Set up figure and subplot using
subplots() - Define an animation function that updates contour data
- Use
FuncAnimation()to create the animation - Display using
show()method
Example
Here's how to create an animated contour plot with random data ?
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
# Create 3D data: 10x10 grid with 8 time frames
data = np.random.randn(800).reshape(10, 10, 8)
fig, ax = plt.subplots()
def animate(frame):
ax.clear()
ax.contourf(data[:, :, frame])
ax.set_title(f'Contour Animation - Frame {frame}')
# Create animation with 8 frames, 50ms intervals
ani = animation.FuncAnimation(fig, animate, frames=8, interval=50, blit=False)
plt.show()
Advanced Example with Custom Colormap
You can enhance the animation with custom colormaps and smoother data ?
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
# Create smoother data using sine waves
x = np.linspace(0, 2*np.pi, 20)
y = np.linspace(0, 2*np.pi, 20)
X, Y = np.meshgrid(x, y)
fig, ax = plt.subplots(figsize=(8, 6))
def animate(frame):
ax.clear()
# Create time-varying function
Z = np.sin(X + frame/10) * np.cos(Y + frame/10)
# Create contour plot with custom colormap
contour = ax.contourf(X, Y, Z, levels=20, cmap='viridis')
ax.set_title(f'Animated Sine Wave Contours - Time: {frame/10:.1f}')
ax.set_xlabel('X')
ax.set_ylabel('Y')
return contour.collections
# Create animation with 100 frames
ani = animation.FuncAnimation(fig, animate, frames=100, interval=100, blit=False)
plt.show()
Key Parameters
| Parameter | Description | Example Value |
|---|---|---|
frames |
Number of animation frames | 8, 100 |
interval |
Delay between frames (milliseconds) | 50, 100 |
blit |
Optimize drawing for speed | False (safer for contours) |
Saving the Animation
You can save the animated contour plot as a GIF or MP4 file ?
# Save as GIF (requires pillow: pip install pillow)
ani.save('contour_animation.gif', writer='pillow', fps=10)
# Save as MP4 (requires ffmpeg)
ani.save('contour_animation.mp4', writer='ffmpeg', fps=10)
Conclusion
Use FuncAnimation with contourf() to create smooth animated contour plots. Remember to clear the axes in each frame and set blit=False for contour animations to work properly.
Advertisements
