How to animate a Seaborn heatmap or correlation matrix(Matplotlib)?

To animate a Seaborn heatmap or correlation matrix, we can use matplotlib's FuncAnimation class to create dynamic visualizations. This technique is useful for showing how data changes over time or displaying random data patterns.

Basic Setup

First, let's set up the required imports and figure configuration ?

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib import animation

# Set figure size and layout
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

Creating an Animated Heatmap

Here's how to create an animated heatmap with randomly changing data ?

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib import animation

# Configure plot settings
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

# Create figure and initial data
fig = plt.figure()
dimension = (5, 5)

# Initialize with random data
data = np.random.rand(dimension[0], dimension[1])
sns.heatmap(data, vmax=0.8, cmap='viridis')

def init():
    """Initialize the first frame with zeros"""
    plt.clf()  # Clear the figure
    sns.heatmap(np.zeros(dimension), vmax=0.8, cbar=False, cmap='viridis')
    return []

def animate(frame):
    """Animation function called for each frame"""
    plt.clf()  # Clear previous heatmap
    data = np.random.rand(dimension[0], dimension[1])
    sns.heatmap(data, vmax=0.8, cbar=False, cmap='viridis',
                annot=True, fmt='.2f', square=True)
    plt.title(f'Animated Heatmap - Frame {frame + 1}')
    return []

# Create animation
anim = animation.FuncAnimation(fig, animate, init_func=init, 
                             frames=20, repeat=False, interval=500)

plt.show()

Animating a Correlation Matrix

For a more realistic example, let's animate a correlation matrix with evolving relationships ?

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib import animation
import pandas as pd

# Set up the figure
plt.rcParams["figure.figsize"] = [8.00, 6.00]
fig, ax = plt.subplots()

# Variable names for correlation matrix
variables = ['A', 'B', 'C', 'D', 'E']
n_vars = len(variables)

def generate_corr_matrix(frame):
    """Generate a correlation matrix that changes over time"""
    # Create time-varying correlations
    t = frame / 10.0
    base_corr = np.eye(n_vars)
    
    # Add some time-varying correlations
    for i in range(n_vars):
        for j in range(i+1, n_vars):
            correlation = 0.5 * np.sin(t + i + j) + 0.3 * np.cos(t * 2 + i - j)
            correlation = np.clip(correlation, -0.8, 0.8)
            base_corr[i, j] = base_corr[j, i] = correlation
    
    return base_corr

def animate_corr(frame):
    """Animation function for correlation matrix"""
    ax.clear()
    corr_matrix = generate_corr_matrix(frame)
    
    # Create DataFrame for better labels
    corr_df = pd.DataFrame(corr_matrix, index=variables, columns=variables)
    
    sns.heatmap(corr_df, annot=True, cmap='RdBu_r', center=0,
                square=True, linewidths=0.5, cbar_kws={"shrink": 0.8},
                vmin=-1, vmax=1, ax=ax, fmt='.2f')
    
    ax.set_title(f'Dynamic Correlation Matrix - Time Step {frame + 1}')

# Create animation
anim = animation.FuncAnimation(fig, animate_corr, frames=30, 
                             interval=300, repeat=True)

plt.tight_layout()
plt.show()

Key Parameters

Understanding the important parameters for animation ?

Parameter Purpose Common Values
frames Number of animation frames 20-100
interval Delay between frames (ms) 100-1000
repeat Loop animation True/False
vmax/vmin Color scale limits Fixed values for consistency

Best Practices

For smooth animations, consider these tips ?

  • Clear previous plots: Use plt.clf() or ax.clear() to avoid overlapping
  • Fix color scales: Set vmin and vmax to keep colors consistent
  • Optimize performance: Use cbar=False in animation frames to speed up rendering
  • Add context: Include frame numbers or time information in titles

Saving Animations

To save your animation as a GIF or video file ?

# Save as GIF (requires pillow or imageio)
anim.save('heatmap_animation.gif', writer='pillow', fps=2)

# Save as MP4 (requires ffmpeg)
anim.save('heatmap_animation.mp4', writer='ffmpeg', fps=5)

Conclusion

Animating Seaborn heatmaps using matplotlib's FuncAnimation creates engaging visualizations for time-series data or dynamic patterns. Remember to clear previous plots, fix color scales, and optimize performance for smooth animations.

Updated on: 2026-03-26T00:03:38+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements