Seaborn自定义范围热图 [英] Seaborn custom range heatmap
问题描述
我需要根据以下要求构建自定义的类似于海图的热图:
I need to build custom seaborn heatmap-like plot according to these requirements:
import pandas as pd
df = pd.DataFrame({"A": [0.3, 0.8, 1.3],
"B": [4, 9, 15],
"C": [650, 780, 900]})
df_info = pd.DataFrame({"id": ["min", "max"],
"A": [0.5, 0.9],
"B": [6, 10],
"C": [850, 880]})
df_info = df_info.set_index('id')
df
A B C
0 0.3 4 650
1 0.8 9 780
2 1.3 15 900
df_info
id A B C
min 0.5 6 850
max 0.9 10 880
df
中的每个值都应在 df_info
中定义的范围内.
例如,如果 A
列的值在0.5到0.9之间,则认为它们是正常的.超出范围的值应使用自定义的热图着色.
Each value within df
is supposed to be within a range defined in df_info
.
For example the values for the column A
are considered normal if they are within 0.5 and 0.9. Values that are outside the range should be colorized using a custom heatmap.
尤其是:
- 落入为每一列定义的范围内的值,不要是白色背景单元格上的彩色纯黑色文本. 该列的
- 小于
min
的值应使用彩色显示,例如蓝色.它们的值从最小值开始越低,蓝色阴影越深. 该列的 - 高于
max
的值应着色,例如用红色.它们的值越高,红色阴影越深.
- Values that fall within the range defined for each column should not be colorized, plain black text on white background cell.
- Values lower than
min
for that column should be colorized, for example in blue. The lower their values from the min the darker the shade of blue. - Values higher than
max
for that column should be colorized, for example in red. The higher their values from the max the darker the shade of red.
问:我不知道如何使用标准热图来实现这一点,我什至不确定我是否可以通过热图来实现这一点.有什么建议吗?
Q: I wouldn't know how to approach this with a standard heatmap, I'm not even sure I can accomplish this with a heatmap plot. Any suggestion?
推荐答案
据我所知,热图只能具有一个比例值.我建议规范化 df
数据框中的数据,以便每一列中的值都遵循:
As far as I know, a heatmap can only have one scale of values. I would suggest normalizing the data you have in the df
dataframe so the values in every column follow:
- 介于
0
和1
之间(如果值介于df_info
的min
max 之间)代码>
- 低于
0
,如果该值低于df_info
的min
- 在
1
之上,如果该值高于df_info
的max
- between
0
and1
if the value is betweendf_info
'smin
max
- below
0
if the value is belowdf_info
'smin
- above
1
if the value is abovedf_info
'smax
要标准化您的数据框,请使用:
To normalize your dataframe use :
for col in df:
df[col] = (df[col] - df_info[col]['min']) / (df_info[col]['max'] - df_info[col]['min'])
最后,使用以下代码创建颜色编码的热图:
Finally, to create the color-coded heatmap use :
import seaborn as sns
from matplotlib.colors import LinearSegmentedColormap
vmin = df.min().min()
vmax = df.max().max()
colors = [[0, 'darkblue'],
[- vmin / (vmax - vmin), 'white'],
[(1 - vmin)/ (vmax - vmin), 'white'],
[1, 'darkred']]
cmap = LinearSegmentedColormap.from_list('', colors)
sns.heatmap(df, cmap=cmap, vmin=vmin, vmax=vmax)
使用 vmin
和 vmax
进行的其他计算允许根据最小和最大差异来动态缩放颜色图.
The additional calculations with vmin
and vmax
allow a dynamic scaling of the colormap depending on the differences with the minimums and maximums.
使用您的输入数据框,我们有以下热图:
Using your input dataframe we have the following heatmap:
这篇关于Seaborn自定义范围热图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!