热图中带有分类数据的标点位置(海床)

问题描述 投票:0回答:1

我正试图绘制我的预测的混淆矩阵。我的数据是多类数据(13个不同的标签),所以我使用热图。

正如你所看到的,我的热图看起来大致不错,但标签的位置有点偏离:y刻度应该更低一点,x刻度应该更靠右一点。我想把两个轴的刻度移动一点,使它们与每个方块的中心对齐。

My Confusion Matrix

我的代码。

sns.set()
my_mask = np.zeros((con_matrix.shape[0], con_matrix.shape[0]), dtype=int)
for i in range(con_matrix.shape[0]):
    for j in range(con_matrix.shape[0]):
        my_mask[i][j] = con_matrix[i][j] == 0 

fig_dims = (10, 10)
plt.subplots(figsize=fig_dims)
ax = sns.heatmap(con_matrix, annot=True, fmt="d", linewidths=.5, cmap="Pastel1", cbar=False, mask=my_mask, vmax=15)
plt.xticks(range(len(party_names)), party_names, rotation=45)
plt.yticks(range(len(party_names)), party_names, rotation='horizontal')
plt.show()

为了便于复制,以下是我的代码 con_matrixparty_names 硬编码。

import numpy as np
from matplotlib import pyplot as plt
import seaborn as sns 

con_matrix = np.array([[55, 0, 0, 0,0, 0, 0,0,0,0,0,0,2], [0,199,0,0,0,0,0,0,0,0,2,0,1],
 [0, 0,52,0,0,0,0,0,0,0,0,0,1],
 [0,0,0,39,0,0,0,0,0,0,0,0,0],
 [0,0,0,0,90,0,0,0,0,0,0,4,3],
 [0,0,0,1,0,35,0,0,0,0,0,0,0],
 [0,0,0,0,5,0,26,0,0,1,0,1,0],
 [0,5,0,0,0,1,0,44,0,0,3,0,1],
 [0,1,0,0,0,0,0,0,52,0,0,0,0],
 [0,1,0,0,2,0,0,0,0,235,0,1,1],
 [1,2,0,0,0,0,0,3,0,0,34,0,3],
 [0,0,0,0,5,0,0,0,0,1,0,40,0],
 [0,0,0,0,0,0,0,0,0,1,0,0,46]])

party_names = ['Blues', 'Browns', 'Greens', 'Greys', 'Khakis', 'Oranges', 'Pinks', 'Purples', 'Reds', 'Turquoises', 'Violets', 'Whites', 'Yellows']

我已经尝试与 position 不同轴的参数,但结果并不理想。在这个网站上也找不到确切的答案(至少没有一个适用于分类数据的解决方案)。

我是seaborn可视化的新手,如果有任何改进的解释,我将非常感激(不仅是我的问题,而且是我的代码& 可视化)。

matplotlib data-visualization seaborn heatmap
1个回答
1
投票

你可以将两个ticklabels偏移0.5个,以获得所需的对齐方式。为了做到这一点,我使用了NumPy的 arange 使得整个数组的向量加法为0.5。

plt.xticks(np.arange(len(party_names))+0.5, party_names, rotation=45)
plt.yticks(np.arange(len(party_names))+0.5, party_names, rotation='horizontal')

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.