简体   繁体   English

如何在Python和Seaborn中使用sns.heatmap的annot方法来提供自定义标签?

[英]How to use `annot` method of `sns.heatmap` to give custom labels, in Python and Seaborn?

How can I use the annot method of sns.heatmap to give it a custom naming scheme? 如何使用sns.heatmapannot方法sns.heatmap提供自定义命名方案?

Essentially, I want to drop all the labels that are lower than my threshold (0 in this case). 本质上,我想删除所有低于阈值(在这种情况下为0)的标签。 I tried doing what @ojy said in Custom Annotation Seaborn Heatmap but I'm getting the following error. 我尝试执行@ojy在“ 自定义批注Seaborn Heatmap”中所说的内容,但出现以下错误。 I saw an example where somebody iterated through every cell, is that the only way to do it? 我看到一个示例,其中有人遍历每个单元格,这是唯一的方法吗?

Seaborn documentation:
annot : bool or rectangular dataset, optional
If True, write the data value in each cell. If an array-like with the same shape as data, then use this to annotate the heatmap instead of the raw data.

So I tried the following: 所以我尝试了以下方法:

# Load Datasets
from sklearn.datasets import load_iris
iris = load_iris()
DF_X = pd.DataFrame(iris.data, index = ["%d_%d"%(i,c) for i,c in zip(range(X.shape[0]), iris.target)], columns=iris.feature_names)

# Correlation
DF_corr = DF_X.corr()

# Figure
fig, ax= plt.subplots(ncols=2, figsize=(16,6))
sns.heatmap(DF_corr, annot=True, ax=ax[0])

# Masked Figure
threshold = 0
DF_mask = DF_corr.copy()
DF_mask[DF_mask < threshold] = 0
sns.heatmap(DF_mask, annot=True, ax=ax[1])

# Annotating
Ar_annotation = DF_mask.as_matrix()
Ar_annotation[Ar_annotation == 0] = None
Ar_annotation
# array([[ 1.        ,         nan,  0.87175416,  0.81795363],
#        [        nan,  1.        ,         nan,         nan],
#        [ 0.87175416,         nan,  1.        ,  0.9627571 ],
#        [ 0.81795363,         nan,  0.9627571 ,  1.        ]])
print(DF_mask.shape, Ar_annotation.shape)
# (4, 4) (4, 4)

sns.heatmap(DF_mask, annot=Ar_annotation, fmt="")

# ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

在此处输入图片说明

Before mask (left), after mask (right) 遮罩之前(左),遮罩之后(右)

That's easy! 这很容易!

Update to 0.7.1 and restart Jupyter kernel. 更新到0.7.1并重新启动Jupyter内核。

https://github.com/mwaskom/seaborn/issues/981 https://github.com/mwaskom/seaborn/issues/981

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM