Seaborn 热图按行颜色

Ian*_*son 1 python matplotlib heatmap seaborn

我有一个网络图。

网络

每个节点都是一个案例,每条边都是一个 CPT。

我曾经community.best_partition将图表分成四个社区(用颜色标记)。

为了更好地可视化我使用的每个社区中共享的 CPT 和案例量plt.subplots,并sns.heatmap创建了四个社区之间具有相似匹配颜色的热图。

热图

生成热图的代码:

fig, axs = plt.subplots(nrows=4, figsize=(16,8), sharex=True)

cmaps = ['Blues', 'Oranges', 'Greens', 'Reds']

comms = range(4)

for ax, cmap, comm in zip(axs, cmaps, comms):
    sns.heatmap(
        data=_.loc[[comm]],
        ax=ax,
        cmap=cmap,
        annot=True,
        annot_kws={
            'fontsize' : 12
        },
        fmt='g',
        cbar=False,
        robust=True,
    )

    ax.set_ylabel('Community')

    ax.set_xlabel('');
Run Code Online (Sandbox Code Playgroud)

问题

有没有办法按sns.heatmap行(在本例中为社区)指定颜色,而无需创建 4 个单独的热图?

这是一些示例数据:

cpt   52320  52353  52310  49568  50432  52234  52317  50435  52354  52332
comm                                                                      
0       NaN    3.0    NaN    1.0    1.0    NaN    2.0    2.0    NaN    3.0
1       1.0   30.0    NaN    NaN    NaN    1.0    NaN    NaN    NaN   20.0
2       NaN    NaN  160.0    NaN    NaN    NaN    NaN    NaN    NaN    NaN
3       NaN    7.0    NaN    NaN    NaN    NaN    NaN    NaN    1.0   12.0
Run Code Online (Sandbox Code Playgroud)

Diz*_*ahi 5

我不认为你可以使用seaborn的热图来做到这一点,但你可以使用重新创建输出imshow()

d = """      52320  52353  52310  49568  50432  52234  52317  50435  52354  52332                                                                     
0       NaN    3.0    NaN    1.0    1.0    NaN    2.0    2.0    NaN    3.0
1       1.0   30.0    NaN    NaN    NaN    1.0    NaN    NaN    NaN   20.0
2       NaN    NaN  160.0    NaN    NaN    NaN    NaN    NaN    NaN    NaN
3       NaN    7.0    NaN    NaN    NaN    NaN    NaN    NaN    1.0   12.0"""
df = pd.read_csv(StringIO(d), sep='\\s+')

N_communities = df.index.size
N_cols = df.columns.size
cmaps = ['Blues', 'Oranges', 'Greens', 'Reds']

fig, ax = plt.subplots()

for i,((idx,row),cmap) in enumerate(zip(df.iterrows(), cmaps)):
    ax.imshow(np.vstack([row.values, row.values]), aspect='auto', extent=[-0.5,N_cols-0.5,i,i+1], cmap=cmap)
    for j,val in enumerate(row.values):
        vmin, vmax = row.agg(['min','max'])
        vmid = (vmax-vmin)/2
        if not np.isnan(val):
            ax.annotate(val, xy=(j,i+0.5), ha='center', va='center', color='black' if (val<=vmid or vmin==vmax) else 'white')
ax.set_ylim(0,N_communities)

ax.set_xticks(range(N_cols))
ax.set_xticklabels(df.columns, rotation=90, ha='center')

ax.set_yticks(0.5+np.arange(N_communities))
ax.set_yticklabels(df.index)
ax.set_ylabel('Community')

ax.invert_yaxis()

fig.tight_layout()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述