如何使用 matplotlib FuncAnimation 为热图制作动画?

How to use matplotlib FuncAnimation to animate a heatmap?

我正在尝试通读 documentation 以便 matplotlib.animation.FuncAnimation 制作热图动画。

当我 运行 下面的代码时,我没有收到任何错误,并且确实出现了热图,但它似乎不是动画。

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()

这段代码的结果好像是rnd_data的单帧,即第一个数组rnd_data[0]。我尝试将 framesinterval 的数量更改为更大的数字,因为我认为它的动画速度太快以至于我看不到,但这似乎没有用。

我是不是做错了什么?我想当我为这样的数据集绘制热图时,我应该能够看到绘图的像素发生变化并像白噪声一样四处移动,但它不起作用。如何制作热图动画?

为了运行正确的动画,你必须使用:

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

以便您指定热图沿第三轴随时间变化。
完整代码如下,为了正确添加颜色条,我做了一些更改:

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()

这给了我这个动画: