简体   繁体   中英

Seaborn Heatmap Color By Row

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

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM