How to use matplotlib FuncAnimation to animate a heatmap?

Viewed 1580

I'm trying to read through the documentation for matplotlib.animation.FuncAnimation to animate a heatmap.

I don't get any errors when I run the code below, and a heatmap plot does appear, but it doesn't seem animated.

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


# generate random noise for the heatmap
rnd_data = np.random.normal(0, 1, (500, 100, 100))

fig, ax = plt.subplots(figsize=(12,10))

def my_func(i):
    sns.heatmap(rnd_data[i])

anim = matplotlib.animation.FuncAnimation(fig=fig, func=my_func, frames=200, interval=500, blit=False)
plt.show()

The result of this code seems to be a single frame of rnd_data, namely the first array rnd_data[0]. I tried changing the number of frames and interval to larger numbers as I thought it was animating too fast for me to see, but this doesn't seem to have worked.

Am I doing something wrong here? I think I should be able to see the pixels of the plot change and move around like white noise when I plot the heatmap for such a dataset, but it isn't working. How can I animate the heatmap?

1 Answers

In order to run correctly the animation, you have to use:

sns.heatmap(rnd_data[..., i])

so that you specify that the heatmap changes over time along the third axis.
The full code is below, I changed something in order to add correctly the colorbar:

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

# generate random noise for the heatmap
rnd_data = np.random.normal(0, 1, (500, 100, 100))

def my_func(i):
    ax.cla()
    sns.heatmap(rnd_data[i, ...],
                ax = ax,
                cbar = True,
                cbar_ax = cbar_ax,
                vmin = rnd_data.min(),
                vmax = rnd_data.max())

grid_kws = {'width_ratios': (0.9, 0.05), 'wspace': 0.2}
fig, (ax, cbar_ax) = plt.subplots(1, 2, gridspec_kw = grid_kws, figsize = (12, 8))
anim = FuncAnimation(fig = fig, func = my_func, frames = 200, interval = 50, blit = False)

plt.show()

which gives me this animation:

enter image description here

Related