使用两种颜色为 seaborn 热图中的不同行着色,将行分成两部分

Use two colors to color different rows in seaborn heatmap split the rows into two

我有以下数据框:

fruits={'fruit':['apple1','apple2','banana1','banan2','peach1','peach2'],'1':[0,0,0,1,0,1],'2':[1,1,0,1,1,1],'3':[1,1,1,1,0,0],'4':[0,1,1,1,1,1]}
df_fruits=pd.DataFrame(data=fruits)
df_fruits=df_fruits.set_index('fruit')


>>>     1   2   3   4
fruit               
apple1  0   1   1   0
apple2  0   1   1   1
banana1 0   0   1   1
banan2  1   1   1   1
peach1  0   1   0   1
peach2  1   1   0   1

我正在尝试创建某种热图,因此如果值为 1,它将获得颜色,如果值为零,将获得颜色 grey.In 除此之外,这就是问题所在,我想给出所有第一颜色为蓝色的水果和所有第二颜色为绿色的水果。 我尝试使用提到的脚本 但我在不需要的位置的单元格上出现白线,将每一行分成两部分:

N_communities = df_fruits.index.size
N_cols = df_fruits.columns.size
cmaps = ['Blues','Greens','Blues','Greens','Blues','Greens','Blues','Greens','Blues','Greens','Blues','Greens','Blues','Greens','Blues','Greens','Blues','Greens','Blues','Greens','Blues','Greens','Blues','Greens','Blues','Greens','Blues','Greens','Blues','Greens']

fig, ax = plt.subplots(figsize=(10,8))

for i,((idx,row),cmap) in enumerate(zip(df_fruits.iterrows(), cmaps)):
    ax.imshow(np.vstack([row.values, row.values]), aspect='equal', 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_fruits.columns, rotation=90, ha='center')

ax.set_yticks(0.5+np.arange(N_communities))
ax.set_yticklabels(df_fruits.index)
ax.set_ylabel('Index')
ax.hlines([2,4],color="black" ,*ax.get_xlim())
ax.invert_yaxis()

fig.tight_layout()

如您所见,看起来苹果 1 有两行,苹果 2 有两行等等,而我想每行各有一行。 我试过玩这个范围,但无法摆脱那些线。

我的最终目标 - 数据帧中的每一行在热图中都有一行,当水果以 1 结束时是蓝色的,水果以 2 结束时是绿色的(仅当值为 1) 。如果值为零,它将是灰色的。

编辑: 我已经按照建议使用了 ax.grid(False) 但仍然不好,因为线条消失了。我还发现绘图是错误的:

如您所见,行“banana2”本来应该是绿色的,但实际上是白色的。

您可以使用 sns.heatmapmask 选项:

mask: If passed, data will not be shown in cells where mask is True. Cells with missing values are automatically masked.

因此,要绘制蓝色的 fruit1 方块,mask 得出 fruit2 的值,反之亦然。

fruit1/fruit2 热图可以通过保存坐标轴句柄 ax 并与 ax=ax:

重复使用来绘制在一起
import pandas as pd
import seaborn as sns

fruits = {'fruit':['apple1','apple2','banana1','banana2','peach1','peach2'],'1':[0,0,0,1,0,1],'2':[1,1,0,1,1,1],'3':[1,1,1,1,0,0],'4':[0,1,1,1,1,1]}
df_fruits = pd.DataFrame(data=fruits)
df_fruits = df_fruits.set_index('fruit')

# *** this line is needed for seaborn 0.10.1 (not needed for 0.11.1) ***
df_fruits = df_fruits.astype('float')

# common settings: linewidths for grid lines, hide colorbar, set square aspect
kwargs = dict(linewidths=1, cbar=False, square=True)

# plot initial gray squares and save heatmap handle as ax
ax = sns.heatmap(df_fruits, cmap='Greys_r', alpha=0.2, **kwargs)

# iterate ending:cmap pairs
cmaps = {'1': 'Blues_r', '2': 'Greens_r'}
for ending, cmap in cmaps.items():
    
    # create mask for given fruit ending
    mask = df_fruits.apply(
        lambda x: x if x.name.endswith(ending) else 0,
        result_type='broadcast',
        axis=1,
    ).eq(0)
    
    # plot masked heatmap on reusable ax
    sns.heatmap(df_fruits, mask=mask, cmap=cmap, ax=ax, **kwargs)