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 3D plot_surface in Matplotlib?
To animate 3D plot_surface in Matplotlib, we can create dynamic surface plots that change over time. This technique is useful for visualizing time-dependent data or mathematical functions that evolve.
Key Components
The animation requires several key components ?
- Initialize variables for number of mesh grids (N), frequency per second (fps), and frame numbers (frn)
- Create x, y and z arrays for the surface mesh
- Make a function to generate z-array values for each frame
- Define an update function that removes the previous plot and creates a new surface
- Use FuncAnimation to orchestrate the animation
Example
Here's a complete example that animates a 3D Gaussian surface ?
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
# Animation parameters
N = 50
fps = 250
frn = 75
# Create mesh grid
x = np.linspace(-4, 4, N + 1)
x, y = np.meshgrid(x, x)
zarray = np.zeros((N + 1, N + 1, frn))
# Define function to animate
f = lambda x, y, sig: 1 / np.sqrt(sig) * np.exp(-(x ** 2 + y ** 2) / sig ** 2)
# Generate z-values for each frame
for i in range(frn):
zarray[:, :, i] = f(x, y, 1.5 + np.sin(i * 2 * np.pi / frn))
def change_plot(frame_number, zarray, plot):
plot[0].remove()
plot[0] = ax.plot_surface(x, y, zarray[:, :, frame_number], cmap="afmhot_r")
# Create figure and 3D subplot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Initial plot
plot = [ax.plot_surface(x, y, zarray[:, :, 0], color='0.75', rstride=1, cstride=1)]
# Set axis properties
ax.set_zlim(0, 1.1)
ax.axis('off')
# Create animation
ani = animation.FuncAnimation(fig, change_plot, frn, fargs=(zarray, plot), interval=1000 / fps)
plt.show()
Output

How It Works
The animation works by creating multiple z-arrays for different time frames. The change_plot function removes the previous surface and draws a new one for each frame. The FuncAnimation class manages the timing and calls the update function repeatedly.
Key Parameters
- N − Controls mesh resolution (higher = smoother surface)
- fps − Frames per second for animation speed
- frn − Total number of animation frames
- interval − Time between frames in milliseconds
Conclusion
Animating 3D surfaces in Matplotlib requires creating multiple z-arrays and using FuncAnimation to update the plot. This technique is perfect for visualizing dynamic mathematical functions or time-series data in three dimensions.
