【问题标题】:seaborn heatmap: y axis ticks and annotseaborn 热图:y 轴刻度和注释
【发布时间】: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


【解决方案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.

【讨论】:

  • 就是这样!!我根据您的评论设置了轴限制,并且效果很好。太感谢了!!我已经花了几个小时试图弄清楚:)
猜你喜欢
  • 1970-01-01
  • 2017-05-11
  • 1970-01-01
  • 2016-03-17
  • 2021-12-20
  • 1970-01-01
  • 2019-08-25
  • 2021-11-07
相关资源
最近更新 更多