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

时间:2020-06-16 14:46:58

标签: python python-3.x matplotlib animation heatmap

我正在尝试通读matplotlib.animation.FuncAnimation的{​​{3}}来制作热图动画。

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

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的数目更改为更大的数目,因为我认为动画制作太快了,以至于我看不到,但这似乎没有用。

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

1 个答案:

答案 0 :(得分:1)

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

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

这给了我这个动画:

enter image description here