0
如何使用sns.heatmap
的annot
方法爲其提供自定義命名方案?如何在Python和Seaborn中使用`sns.heatmap`的`annot`方法給自定義標籤?
本質上,我想刪除所有低於我的閾值(在這種情況下爲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()
面具(左)之前,面膜(右)