【问题标题】:2 confusion matrix, 1 colorbar2 个混淆矩阵,1 个颜色条
【发布时间】:2019-03-23 15:58:48
【问题描述】:

我想生成两个混淆矩阵并且只显示一个颜色条。我基本上是在尝试将this scikit-learn codethis answer 合并。

我的代码如下所示:

import numpy as np
import matplotlib.pyplot as plt


fig, axes = plt.subplots(nrows=1, ncols=2)
classes = ["A", "B"]
for i, ax in enumerate(axes.flat):
    cm = np.random.random((2,2))
    im = ax.imshow(cm, vmin=0, vmax=1)
    plt.title("Title {}".format(i))
    tick_marks = np.arange(2)
    plt.xticks(tick_marks, classes, rotation=45)
    plt.yticks(tick_marks, classes)

    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        plt.text(j, i, format(cm[i, j], '.5f'),
                 horizontalalignment="center",
                 color="white")

    plt.ylabel('True label')
    plt.xlabel('Predicted label')
    plt.tight_layout()

fig.subplots_adjust(right=0.8)
cbar_ax = fig.add_axes([0.88, 0.15, 0.05, 0.6])
fig.colorbar(im, cax=cbar_ax)

plt.show()

但这是结果:

所以一切都被绘制在最后一张图像上。 两个问题:

  • 如何将两者分开?
  • 如何从矩阵开始的颜色栏开始,即使它没有标签?

【问题讨论】:

标签: python python-3.x matplotlib scikit-learn


【解决方案1】:

所有元素都绘制在最后一张图像上,因为您将pyplot (plt.xxxxx()) 接口与面向对象的接口混合在一起。部分解释请参考this questionthis one

对于彩条,有很多方法可以获得大小合适的彩条(例如,@DavidG 建议使用GridSpecAxisDivider)。因为你有两个使用imshow 的轴,所以我建议使用ImageGrid 代替,就像this answer to a similar question 一样。

您的代码应为:

import itertools
from mpl_toolkits.axes_grid1 import ImageGrid


classes = ["A", "B"]

fig = plt.figure()
grid = ImageGrid(fig, 111,          # as in plt.subplot(111)
                 nrows_ncols=(1,2),
                 axes_pad=0.15,
                 cbar_location="right",
                 cbar_mode="single",
                 cbar_size="7%",
                 cbar_pad=0.15,
                 )


for i, ax in enumerate(grid[:2]):
    cm = np.random.random((2,2))
    im = ax.imshow(cm, vmin=0, vmax=1)
    ax.set_title("Title {}".format(i))  # ax.___ instead of plt.___
    tick_marks = np.arange(2)
    ax.set_xticks(tick_marks)  # Warning: different signature for [x|y]ticks in pyplot and OO interface
    ax.set_xticklabels(classes, rotation=45)
    ax.set_yticks(tick_marks)
    ax.set_yticklabels(classes)

    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        ax.text(j, i, format(cm[i, j], '.5f'),
                 horizontalalignment="center",
                 color="white")

    ax.set_ylabel('True label')
    ax.set_xlabel('Predicted label')

fig.tight_layout()
fig.subplots_adjust(right=0.8)
fig.colorbar(im, cax=ax.cax)

plt.show()

【讨论】:

    猜你喜欢
    • 2022-01-02
    • 2015-07-07
    • 2019-03-28
    • 1970-01-01
    • 1970-01-01
    • 2020-07-09
    • 1970-01-01
    • 1970-01-01
    • 2018-12-17
    相关资源
    最近更新 更多