Python 如何使用matplotlib FuncAnimation设置热图动画?

Python 如何使用matplotlib FuncAnimation设置热图动画?,python,python-3.x,matplotlib,animation,heatmap,Python,Python 3.x,Matplotlib,Animation,Heatmap,我正试图通读formatplotlib.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.norma

我正试图通读for
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\u数据的单个帧
,即第一个数组
rnd\u数据[0]
。我尝试将
帧数
间隔
更改为更大的数字,因为我认为它的动画速度太快,我看不见,但这似乎不起作用


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

要正确运行动画,必须使用:

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笔记本?我想我的问题是我使用的是Jupyter笔记本。因为你的代码在python脚本中运行良好,但在Jupyter笔记本中没有动画。我想知道为什么会这样。再次感谢!要在Jupyter笔记本中运行动画,请阅读以下内容。