You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Seaborn热力图Y轴刻度与单元格标注居中对齐问题求助

解决Seaborn热力图Y轴刻度与单元格标注不对齐的问题

首先,我注意到你的代码里有个小疏漏——没有导入并初始化StandardScaler,这会导致运行时抛出NameError,先补上这部分必要的代码。

接下来回到核心问题:Seaborn绘制热力图时,默认的Y轴刻度是落在单元格的边缘位置,而单元格内的标注是居中的,所以看起来会出现错位。我们可以通过调整Y轴刻度的位置和对齐方式来解决这个问题,具体方案如下:

调整后的完整可运行代码

import numpy as np
import pandas as pd
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn import metrics
from sklearn.preprocessing import StandardScaler  # 补上缺失的导入
import seaborn as sns
import matplotlib.pyplot as plt

bunch = datasets.load_breast_cancer()
def bunch_to_df(bunch):
    data = np.c_[bunch.data, bunch.target]
    columns = np.append(bunch.feature_names, ["target"])
    return pd.DataFrame(data, columns=columns)

df = bunch_to_df(bunch)
x = df[['mean area', 'mean texture']]
y = df.loc[:,['target']].values

sc = StandardScaler()  # 初始化标准化工具
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=0)
x_train = sc.fit_transform(x_train)
x_test = sc.transform(x_test)

logisticRegr = LogisticRegression()
logisticRegr.fit(x_train, y_train.ravel())
predictions = logisticRegr.predict(x_test)
accuracy = logisticRegr.score(x_test, y_test.ravel())
confusion_matrix = metrics.confusion_matrix(y_test, predictions)

fig = plt.figure(figsize=[7,7])
ax = fig.add_subplot(1, 1, 1)
sns.heatmap(confusion_matrix, annot=True, cbar=False, cmap='Blues', ax=ax)

# 关键调整:让Y轴刻度与单元格中心对齐
ax.set_yticks(np.arange(confusion_matrix.shape[0]) + 0.5)
# 可以替换成对应业务的类别名称,比如这里0代表恶性,1代表良性
ax.set_yticklabels(['Malignant', 'Benign'], va='center')

plt.ylabel('Actual Values')
plt.xlabel('Predicted Values')
plt.title('Accuracy Score: {0}'.format(round(accuracy,2)), size = 15)
plt.tight_layout()
plt.show()

关键调整点说明

  • ax.set_yticks(np.arange(confusion_matrix.shape[0]) + 0.5):热力图的每个单元格对应一个区间(比如0-1、1-2),给刻度位置加0.5,就能把刻度从单元格边缘移到中心位置。
  • ax.set_yticklabels(..., va='center'):设置Y轴标签的垂直对齐方式为居中,确保标签和单元格内的标注完全对齐。

如果不需要自定义类别名称,直接用默认的0和1,也可以把set_yticklabels改成ax.set_yticklabels(['0', '1'], va='center'),甚至省略标签参数,只要设置了刻度位置和对齐方式,就能解决错位问题。

内容的提问来源于stack exchange,提问作者Jose Lago

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 09:08:55