son*_*804 3 python visualization seaborn
我正在使用 Seaborn 热图来绘制大型混淆矩阵的输出。由于对角线元素代表正确预测,因此它们更重要的是显示数量/正确率。正如问题所暗示的那样,如何仅注释热图中的对角线条目?
我已经咨询过这个网站https://seaborn.pydata.org/examples/many_pairwise_correlations.html,但它对如何只注释对角线条目没有帮助。希望有人可以帮忙。先感谢您!
这是否有助于您了解您的想法?您给出的 URL 示例没有对角线,我在主对角线下方注释了对角线。要注释您的混淆矩阵对角线,您可以通过将 -1 值更改np.diag(..., -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()
Run Code Online (Sandbox Code Playgroud)