在混淆矩阵的各个方面绘制标签

Plot labels from all sides in confusion matrix

我需要绘制从各个方面注释的混淆矩阵。我在右侧有问题,我想在底部打印相同的标签([...类 names..., 'Total samples', 'Accuracy' 'mIoU']) .此外,顶部刻度似乎与底部刻度不对齐。

这是我尝试过的:

    fig, ax1 = get_new_fig('Conf matrix default', figsize)

    
    ax = sn.heatmap(df_cm, annot=annot, annot_kws={"size": fz}, linewidths=lw, ax=ax1,
                    cbar=cbar, cmap=cmap, linecolor='w', fmt=fmt)

    ax_new = ax.twinx().twiny()

    labels = ['' for _ in range(len(ax.get_xticklabels()))]

    labels[-3] = 'Total samples'
    labels[-2] = 'Accuracy'
    labels[-1] = 'mIoU'

    ticks = [tick for tick in ax.get_xticks()]

    ax_new.set_xticks(ticks)
    ax_new.set_yticks(ticks)
    ax_new.yaxis.set_label_position('right')

    ax_new.set_xticklabels([text.get_text() for text in ax.get_xticklabels()], fontsize=10, rotation=-45)  # top
    ax_new.set_yticklabels(labels, fontsize=10, rotation=-25)  # right

    # set ticklabels
    ax.set_xticklabels(labels, rotation=45, fontsize=10)  # bottom
    ax.set_yticklabels(ax.get_yticklabels(), rotation=25, fontsize=10)  # left

非常感谢任何帮助,因为我不知道我是否遗漏了代码中的某些内容或其他内容。

提前致谢。

问题在于新 ax 的限制。这些需要等于原始 ax 的限制。尤其是原来 ax 的 y 轴被颠倒了,导致新的 y 轴没有可见的刻度标签。不同的限制也阻止了 x 轴刻度的对齐。

ax_new.set_xlim(ax.get_xlim())ax_new.set_ylim(ax.get_ylim()) 应该可以解决问题。 plt.tight_layout() 可以帮助在周围的图中很好地定位所有标签。

右y刻度标签的旋转问题似乎有点难。下面的代码通过将 twinxtwiny 轴分开来解决它:

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np

fig, ax1 = plt.subplots()
ax1.set_title('Conf matrix default')

df_cm = pd.DataFrame(np.random.rand(9, 9), columns=range(1, 10), index=range(1, 10))
ax = sns.heatmap(df_cm, annot=True, annot_kws={"size": 12}, linewidths=2, ax=ax1,
                 cbar=False, linecolor='w', fmt='.2f')

ax_new1 = ax.twinx()
ax_new2 = ax_new1.twiny()

labels = ['' for _ in range(len(ax.get_xticklabels()))]

labels[-3] = 'Total samples'
labels[-2] = 'Accuracy'
labels[-1] = 'mIoU'

ticks = [tick for tick in ax.get_xticks()]

ax_new2.set_xticks(ticks)
ax_new1.set_yticks(ticks)
ax_new1.yaxis.set_label_position('right')

ax_new2.set_xticklabels([text.get_text() for text in ax.get_xticklabels()], fontsize=10, rotation=-45)  # top
ax_new1.set_yticklabels(labels, fontsize=10, rotation=-45)  # right

# set ticklabels
ax.set_xticklabels(labels, rotation=45, fontsize=10)  # bottom
ax.set_yticklabels(ax.get_yticklabels(), rotation=25, fontsize=10)  # left

ax_new2.set_xlim(ax.get_xlim())
ax_new1.set_ylim(ax.get_ylim())

plt.tight_layout()
plt.show()