How to animate a pcolormesh in Matplotlib?

To animate a pcolormesh in Matplotlib, you create a pseudocolor plot and update its data over time using the FuncAnimation class. This technique is useful for visualizing time-varying 2D data like wave propagation or heat distribution.

Basic Steps

The animation process involves these key steps ?

  • Create a figure and subplot

  • Generate coordinate data using numpy.meshgrid()

  • Create initial pcolormesh plot

  • Define animation function to update data

  • Use FuncAnimation to create the animation

Example

Here's a complete example animating a ripple wave pattern ?

import numpy as np
from matplotlib import pyplot as plt, animation

plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True

# Create figure and axis
fig, ax = plt.subplots()

# Create coordinate arrays
x = np.linspace(-3, 3, 91)
y = np.linspace(-3, 3, 91)
t = np.linspace(0, 25, 30)

# Create 3D meshgrid
X3, Y3, T3 = np.meshgrid(x, y, t)

# Generate time-varying wave data
sinT3 = np.sin(2 * np.pi * T3 / T3.max(axis=2)[..., np.newaxis])
G = (X3 ** 2 + Y3 ** 2) * sinT3

# Create initial pcolormesh
cax = ax.pcolormesh(x, y, G[:-1, :-1, 0], vmin=-1, vmax=1, cmap='Blues')
fig.colorbar(cax)

# Animation function
def animate(frame):
    cax.set_array(G[:-1, :-1, frame].flatten())
    return [cax]

# Create animation
anim = animation.FuncAnimation(fig, animate, interval=100, frames=len(t) - 1)
plt.show()

How It Works

Data Generation: The code creates a 3D array where the first two dimensions represent spatial coordinates and the third represents time. The wave pattern is generated using (X² + Y²) * sin(2?t/t_max).

Animation Function: The animate() function updates the pcolormesh data for each frame by calling set_array() with flattened 2D data from the current time slice.

Frame Updates: FuncAnimation calls the animate function repeatedly, passing the current frame number, which corresponds to the time index in our 3D array.

Key Parameters

Parameter Purpose Example Value
vmin, vmax Set colormap range -1, 1
interval Delay between frames (ms) 100
frames Number of animation frames 29
cmap Colormap for visualization 'Blues'

Output

X Y 1.0 0.0 -1.0 Animated Pcolormesh - Wave Propagation Frame updating

Conclusion

Animating a pcolormesh requires creating time-varying 2D data and using FuncAnimation to update the plot. The key is using set_array() to efficiently update data without recreating the entire plot each frame.

Updated on: 2026-03-25T19:50:44+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements