簡體   English   中英

Seaborn 熱圖顏色按行

[英]Seaborn Heatmap Color By Row

我有一個網絡圖。

網絡

每個節點是一個案例,每個邊是一個 CPT。

我使用community.best_partition將圖表分成四個社區(以它們的顏色表示)。

為了更好地可視化每個社區中共享的 CPT 和案例量,我使用plt.subplotssns.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('');

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

我不認為你可以使用 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()

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM