Seaborn热图按行排列颜色 [英] Seaborn Heatmap Color By Row

查看:162
本文介绍了Seaborn热图按行排列颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张网络图.

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

我使用 community.best_partition 将图分成四个社区(以其颜色表示).

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

产生热图的代码:

  fig,axs = plt.subplots(行数= 4,figsize =(16,8),sharex = True)cmaps = [蓝色",橙色",绿色",红色"]通讯=范围(4)适用于zip中的ax,cmap,comm(axs,cmaps,comms):sns.heatmap(数据= _.loc [[comm]],ax = ax,cmap = cmap,annot = True,annot_kws = {'fontsize':12},fmt ='g',cbar = False,健壮=正确,)ax.set_ylabel('社区')ax.set_xlabel(''); 

问题

sns.heatmap 中是否有一种方法可以按行指定颜色(在本例中为社区),而不必创建4个单独的热图?

以下是一些示例数据:

  cpt 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.01 1.0 30.0 NaN NaN NaN 1.0 NaN NaN NaN 20.02 NaN NaN 160.0 NaN NaN NaN NaN NaN NaN NaN NaN3 NaN 7.0 NaN NaN NaN NaN NaN NaN NaN 1.0 12.0 

解决方案

我认为您不能使用seaborn的热图来做到这一点,但是您可以使用 imshow()

  d =""52320 52353 52310 49568 50432 52234 52317 50435 52354 523320 NaN 3.0 NaN 1.0 1.0 NaN 2.0 2.0 NaN 3.01 1.0 30.0 NaN NaN NaN 1.0 NaN NaN NaN 20.02 NaN NaN 160.0 NaN NaN NaN NaN NaN NaN NaN NaN3 NaN 7.0 NaN NaN NaN NaN NaN NaN NaN 1.0 12.0"df = pd.read_csv(StringIO(d),sep ='\\ s +')N_communities = df.index.sizeN_cols = df.columns.sizecmaps = [蓝色",橙色",绿色",红色"]无花果,ax = plt.subplots()对于我,((idx,row),cmap)枚举(zip(df.iterrows(),cmaps)):ax.imshow(np.vstack([row.values,row.values]),Aspect ='auto',scope = [-0.5,N_cols-0.5,i,i + 1],cmap = cmap)对于枚举(row.values)中的j,val:vmin,vmax = row.agg(['min','max'])vmid =(vmax-vmin)/2如果不是np.isnan(val):ax.annotate(val,xy =(j,i + 0.5),ha ='center',va ='center',color ='black'if(val< = vmid或vmin == vmax)否则为'white')ax.set_ylim(0,N_communities)ax.set_xticks(范围(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('社区')ax.invert_yaxis()fig.tight_layout() 

I have a network graph.

Each node is a case and each edge is a CPT.

I used community.best_partition to break the graph into four communities (noted by their colors).

To better visualize the shared CPTs and case volumes in each community I used plt.subplots and sns.heatmap to create four heatmaps with similar matching colors between communities.

Code to produce the heatmaps:

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

Question

Is there a way in sns.heatmap to specify colors by row (in this case, community) without having to create 4 separate heatmaps?

Here is some sample data:

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

解决方案

I don't think you can do that using seaborn's heatmap, but you can recreate the output using 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()

这篇关于Seaborn热图按行排列颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆