Python Seaborn动态更新热图数据

Python Seaborn dynamic update of heatmap data

我想动态更新一个用Seaborn制作的热图,一条一条地添加数据线。 下面的示例代码完成了基础工作,但它似乎没有更新热图,而是在之前的热图中嵌套了一个新热图。

提前感谢您提供的任何 help/solution。

import numpy as np
np.random.seed(0)
import seaborn as sns
import matplotlib.pyplot as plt


data = np.random.rand(120 ,5900)
data_to_draw = np.zeros(shape=(1,5900))
for i,d in enumerate(data):
    # update data to be drawn
    data_to_draw = np.vstack((data_to_draw, data[i]))
    #keep max 5 rows visible
    if data_to_draw.shape[0]>5:
        data_to_draw = data_to_draw[1:]
    
    ax = sns.heatmap(data_to_draw,cmap="coolwarm")

    plt.draw()
    plt.pause(0.1)

我重新构建了您的代码以利用 matplotlib.animation.FuncAnimation
为了避免在每次迭代中绘制新的heatmap和新的colobar,需要通过seaborn.heatmap中的axcbar_ax参数指定在哪个轴上绘制它们。
而且,画好热图后,用ax.cla().

抹掉之前的很方便

完整代码

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


np.random.seed(0)

data = np.random.rand(120, 50)
data_to_draw = np.zeros(shape = (1, 50))

def animate(i):
    global data_to_draw
    data_to_draw = np.vstack((data_to_draw, data[i]))
    if data_to_draw.shape[0] > 5:
        data_to_draw = data_to_draw[1:]

    ax.cla()
    sns.heatmap(ax = ax, data = data_to_draw, cmap = "coolwarm", cbar_ax = cbar_ax)


grid_kws = {'width_ratios': (0.9, 0.05), 'wspace': 0.2}
fig, (ax, cbar_ax) = plt.subplots(1, 2, gridspec_kw = grid_kws, figsize = (10, 8))
ani = FuncAnimation(fig = fig, func = animate, frames = 100, interval = 100)

plt.show()


如果你想保持原来的代码结构,可以应用相同的原则:

import numpy as np

np.random.seed(0)
import seaborn as sns
import matplotlib.pyplot as plt

data = np.random.rand(120, 5900)
data_to_draw = np.zeros(shape = (1, 5900))

grid_kws = {'width_ratios': (0.9, 0.05), 'wspace': 0.2}
fig, (ax, cbar_ax) = plt.subplots(1, 2, gridspec_kw = grid_kws, figsize = (10, 8))

for i, d in enumerate(data):
    # update data to be drawn
    data_to_draw = np.vstack((data_to_draw, data[i]))
    # keep max 5 rows visible
    if data_to_draw.shape[0] > 5:
        data_to_draw = data_to_draw[1:]

    sns.heatmap(ax = ax, data = data_to_draw, cmap = "coolwarm", cbar_ax = cbar_ax)

    plt.draw()
    plt.pause(0.1)