【发布时间】:2020-04-19 04:30:06
【问题描述】:
我正在尝试为简单的混淆矩阵绘制热图。我唯一的问题是 y 轴上的刻度和每个字段内的注释没有与中心对齐。
我曾尝试使用其他回复来解决类似问题,但我未能正确解决...请您帮忙吗?
提前致谢!
代码:
fig = plt.figure(figsize=[7,7])
ax = fig.add_subplot(1, 1, 1)
sns.heatmap(confusion_matrix,annot=True,cbar=False,cmap='Blues')
plt.ylabel('Actual Values')
plt.xlabel('Predicted Values')
plt.title('Accuracy Score: {0}'.format(round(accuracy,2), size = 15))
plt.tight_layout()
plt.show()
根据 cmets 的要求,这里是完整代码,您可以在热图中查看数据的来源:
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
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
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')
plt.ylabel('Actual Values')
plt.xlabel('Predicted Values')
plt.title('Accuracy Score: {0}'.format(round(accuracy,2), size = 15))
plt.tight_layout()
plt.show()
【问题讨论】:
-
能提供头部图的数据源吗?
-
当然!它是来自 sklearn 的乳腺癌数据集。我会用代码更新问题。
-
我假设您要将 y 轴文本对齐为水平?只需将第 4 行切换到 plt.ylabel('Actual Values', rotation = 0)
-
感谢您的更新。正如 Severre 所说,这似乎是 matplotlib 的错误。在我的环境中,它没有问题。我的是 3.1.0 顺便说一句。
标签: python matplotlib seaborn heatmap