如何仅注释海上热图的对角线元素?

时间:2019-11-20 18:41:44

标签: python seaborn visualization

我正在使用Seaborn热图绘制大型混淆矩阵的输出。由于对角线元素代表正确的预测,因此对显示数字/正确率更为重要。正如问题所暗示的,如何仅注释热图中的对角线条目?

我已经浏览了该网站https://seaborn.pydata.org/examples/many_pairwise_correlations.html,但是它对如何仅注释对角线条目没有帮助。希望有人可以提供帮助。预先谢谢你!

1 个答案:

答案 0 :(得分:1)

这是否有助于您了解自己的想法?您提供的URL示例没有对角线,我在主对角线下方标注了对角线。要注释混淆矩阵对角线,可以通过将np.diag(..., -1)中的-1值更改为0来适应我的代码。

请注意,由于我的fmt=''矩阵元素是字符串,因此我在sns.heatmap(...)中添加了附加参数annot

代码

from string import ascii_letters
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

sns.set(style="white")

# Generate a large random dataset
rs = np.random.RandomState(33)
y = rs.normal(size=(100, 26))
d = pd.DataFrame(data=y,
                 columns=list(ascii_letters[26:]))

# Compute the correlation matrix
corr = d.corr()

# Generate a mask for the upper triangle
mask = np.zeros_like(corr, dtype=np.bool)
mask[np.triu_indices_from(mask)] = True

# Set up the matplotlib figure
f, ax = plt.subplots(figsize=(11, 9))

# Generate a custom diverging colormap
cmap = sns.diverging_palette(220, 10, as_cmap=True)

# Generate the annotation
annot = np.diag(np.diag(corr.values,-1),-1)
annot = np.round(annot,2)
annot = annot.astype('str')
annot[annot=='0.0']=''

# Draw the heatmap with the mask and correct aspect ratio
sns.heatmap(corr, mask=mask, cmap=cmap, vmax=.3, center=0,
            square=True, linewidths=.5, cbar_kws={"shrink": .5}, annot=annot, fmt='')

plt.show()

输出 enter image description here