我正在尝试为simpe混淆矩阵绘制热图。我唯一的问题是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()
根据注释中的要求,以下是完整的代码,因此您可以在热图中查看数据的来源:
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()
答案 0 :(得分:1)
我相信这是当前matplotlib版本中的错误。 This post may provide an answer.
您可以尝试使用ax.set_ylim(3.0, 0)
或将matplotlib版本恢复为3.1.0来手动设置轴限制。
如果这不起作用,则可以从Github安装最新版本。 Look at the 'Installing from source' section for instructions.