How to plot an animated image matrix in matplotlib?

To plot an animated image matrix in matplotlib, we can use FuncAnimation to repeatedly update a matrix display. This creates smooth animated visualizations of changing data patterns.

Steps

  • Set the figure size and adjust the padding between and around the subplots.

  • Create a figure and a set of subplots.

  • Make an animation by repeatedly calling a function update.

  • Inside the update method, create a 6×6 dimension of matrix and display the data as an image, i.e., on a 2D regular raster.

  • Turn off the axes using set_axis_off().

  • To display the figure, use show() method.

Basic Animation Example

Here's how to create an animated matrix with random values ?

from matplotlib.animation import FuncAnimation
import matplotlib.pyplot as plt
import numpy as np

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

fig, ax = plt.subplots()

def update(i):
    im_normed = np.random.rand(6, 6)
    ax.clear()
    ax.imshow(im_normed, cmap='viridis')
    ax.set_axis_off()
    ax.set_title(f'Frame {i}')

anim = FuncAnimation(fig, update, frames=10, interval=500)
plt.show()

Advanced Animation with Pattern

Create an animated matrix with a moving pattern ?

from matplotlib.animation import FuncAnimation
import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(figsize=(6, 6))

def update(frame):
    # Create a moving wave pattern
    x = np.linspace(0, 2*np.pi, 8)
    y = np.linspace(0, 2*np.pi, 8)
    X, Y = np.meshgrid(x, y)
    
    # Animated sine wave
    Z = np.sin(X + frame * 0.3) * np.cos(Y + frame * 0.2)
    
    ax.clear()
    im = ax.imshow(Z, cmap='plasma', animated=True)
    ax.set_axis_off()
    ax.set_title(f'Animated Wave Pattern - Frame {frame}')
    
    return [im]

anim = FuncAnimation(fig, update, frames=30, interval=100, blit=True)
plt.tight_layout()
plt.show()

Key Parameters

Parameter Description Example Value
frames Number of animation frames 30
interval Delay between frames (ms) 100
blit Optimize drawing for better performance True

Output

The animation will display a continuously changing matrix pattern, with each frame showing different values or patterns based on your update function.

Animated Matrix Display Frame updates create smooth animation

Conclusion

Use FuncAnimation with imshow() to create animated matrix visualizations. Remember to use ax.clear() in your update function and set appropriate interval values for smooth animation.

Updated on: 2026-03-26T15:20:32+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements