首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在Python和Seaborn中使用`sns.heatmap`的`annot`方法给出自定义标签?

如何在Python和Seaborn中使用`sns.heatmap`的`annot`方法给出自定义标签?
EN

Stack Overflow用户
提问于 2016-08-03 01:24:57
回答 1查看 3.2K关注 0票数 0

如何使用sns.heatmapannot方法为其提供自定义命名方案?

本质上,我想删除所有低于阈值的标签(在本例中为0)。我试着按照@ojy在Custom Annotation Seaborn Heatmap中说的做,但是我得到了下面的错误。我看到一个例子,有人遍历每个单元格,这是唯一的方法吗?

代码语言:javascript
运行
复制
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.

因此,我尝试了以下方法:

代码语言:javascript
运行
复制
# 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()

遮罩前(左)、遮罩后(右)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-08-05 06:35:28

这很简单!

更新到0.7.1并重启Jupyter内核。

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38726886

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档