为Seaborn热图分配特定颜色

问题描述

我正在尝试使用seaborn制作热图,但被卡住以更改特定值的颜色。假设值0应该是白色,值1应该是灰色,然后在上面使用cmap提供的调色板。

试图使用面具,但感到困惑。

import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import pandas as pd

df = pd.read_csv('/home/test.csv',index_col=0)

fig,ax = plt.subplots()
sns.heatmap(df,cmap="Reds",vmin=0,vmax=15)
plt.show()

此为示例数据

TAG     A   B   C   D   E   F   G   H   I   J
TAG_1   1   0   0   5   0   7   1   1   0   10
TAG_2   0   1   0   6   0   6   0   0   0   7
TAG_3   0   1   0   2   0   4   0   0   1   4
TAG_4   0   0   0   3   1   3   0   0   0   10
TAG_5   1   0   1   5   0   2   1   1   0   11
TAG_6   0   0   0   0   0   0   0   0   0   12
TAG_7   0   1   0   0   1   0   0   0   0   0
TAG_8   0   0   0   1   0   0   1   0   1   0
TAG_9   0   0   1   0   0   0   0   0   0   0
TAG_10  0   0   0   0   0   0   0   0   0   0

解决方法

df.set_index('TAG',inplace=True)告诉seaborn标签应该用作标签,而不是数据。

“二进制”色彩图从较低值的白色平滑过渡到最高值的深黑色。玩vminvmax,将vmin=0vmax的值设置为1.5到大约5之间,值0将为白色,而值1将为任何所需的灰色类型。

要设置掩码,应将数据帧转换为2D numpy数组,并且类型为float。

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
from io import StringIO

data_str = StringIO('''TAG     A   B   C   D   E   F   G   H   I   J
TAG_1   1   0   0   5   0   7   1   1   0   10
TAG_2   0   1   0   6   0   6   0   0   0   7
TAG_3   0   1   0   2   0   4   0   0   1   4
TAG_4   0   0   0   3   1   3   0   0   0   10
TAG_5   1   0   1   5   0   2   1   1   0   11
TAG_6   0   0   0   0   0   0   0   0   0   12
TAG_7   0   1   0   0   1   0   0   0   0   0
TAG_8   0   0   0   1   0   0   1   0   1   0
TAG_9   0   0   1   0   0   0   0   0   0   0
TAG_10  0   0   0   0   0   0   0   0   0   0''')

df = pd.read_csv(data_str,delim_whitespace=True)
df.set_index('TAG',inplace=True)
values = df.to_numpy(dtype=float)
ax = sns.heatmap(values,cmap='Reds',vmin=0,vmax=15,square=True)
sns.heatmap(values,xticklabels=df.columns,yticklabels=df.index,cmap=plt.get_cmap('binary'),vmax=2,mask=values > 1,cbar=False,ax=ax)
plt.show()

example plot

或者,可以创建自定义颜色图。这样,颜色栏还将显示调整后的颜色。

cmap_reds = plt.get_cmap('Reds')
num_colors = 15
colors = ['white','grey'] + [cmap_reds(i / num_colors) for i in range(2,num_colors)]
cmap = LinearSegmentedColormap.from_list('',colors,num_colors)
ax = sns.heatmap(df,cmap=cmap,vmax=num_colors,square=True,cbar=False)
cbar = plt.colorbar(ax.collections[0],ticks=range(num_colors + 1))
plt.show()

custom colormap

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...