【问题标题】:How to use `annot` method of `sns.heatmap` to give custom labels, in Python and Seaborn?如何使用`sns.heatmap`的`annot`方法在Python和Seaborn中提供自定义标签?
【发布时间】:2016-08-02 17:24:57
【问题描述】:

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

基本上,我想删除所有低于我的阈值(在本例中为 0)的标签。我尝试按照@ojy 在Custom Annotation Seaborn Heatmap 中所说的进行操作,但出现以下错误。我看到一个例子,有人遍历每个单元格,这是唯一的方法吗?

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.

所以我尝试了以下方法:

# 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()

掩码前(左),掩码后(右)

【问题讨论】:

    标签: python matplotlib heatmap seaborn data-science


    【解决方案1】:

    这很简单!

    更新到 0.7.1 并重启 Jupyter 内核。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-09
      • 1970-01-01
      • 2016-03-29
      • 1970-01-01
      • 2020-02-17
      • 2013-01-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多