【问题标题】:How to use matplotlib FuncAnimation to animate a heatmap?如何使用 matplotlib FuncAnimation 为热图设置动画?
【发布时间】:2020-06-16 14:46:58
【问题描述】:

我正在尝试通读documentationmatplotlib.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 的数量更改为更大的数字,因为我认为它的动画速度太快了,我看不到,但这似乎不起作用。

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

【问题讨论】:

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


    【解决方案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()
    

    这给了我这个动画:

    【讨论】:

    • 感谢您的回答!不过,这似乎对我不起作用-它是绘图,但不是动画。另外,我实际上想及时更改沿第一个轴的热图(即长度为 500),以便热图为 100x100 的正方形,如果问题中不清楚,抱歉
    • 我更新了我的答案以改变热图的形状:现在i(逐帧增加 1 帧)沿着第一个轴(500 个元素长) 并且热图为 100x100。我不知道为什么它在您的情况下没有动画,您是否复制并粘贴了上面的整个代码?您使用的是 IDE(如 PyCharm)还是 Jupyter Notebook?
    • 我认为我的问题是我使用的是 jupyter 笔记本。因为您的代码在 python 脚本中运行良好,但在 jupyter notebook 中没有动画效果。我想知道为什么会这样。再次感谢!
    • 要在 Jupyter Notebook 中运行动画,请阅读guide
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-12
    • 2014-01-08
    • 1970-01-01
    • 1970-01-01
    • 2021-10-27
    相关资源
    最近更新 更多