我有以下数据框:
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,它将获得颜色,如果为零,则会获得灰色。除此之外,这就是问题,我想为所有水果提供第一颜色蓝色,所有排名第二的水果都是绿色。
我尝试使用提到的脚本here https://stackoverflow.com/questions/60325792/seaborn-heatmap-color-by-row但我在不需要的位置的单元格上看到白线,将每一行分为两行:
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 时)。如果值为零,它将是灰色的。
Edit:
I have used the the ax.grid(False) as suggested but is still not goood as the lines dissapear. also I found out that the plotting is wrong:
正如您所看到的,“banana 2”行应该是绿色的,但实际上是白色的。