【问题标题】:How to show all the labels in subplot. I have 12 labels of which I have to plot a confusion matrix. But only 6 of them are visible如何在子图中显示所有标签。我有 12 个标签,我必须绘制一个混淆矩阵。但其中只有 6 个可见
【发布时间】:2020-08-11 22:10:48
【问题描述】:

我想绘制一个包含 12 个数据的混淆矩阵,所以我制作了 12 个标签来绘制混淆矩阵,12 个数据的绘图正确,但 x 标签和 y 标签只显示了一半。

我用过这个sn-p--:

import matplotlib.pyplot as plt

labels = ['1','2','3','4','5','6','7','8','9','10','11','12']
cm = confusion_matrix(actualList, predictList, labels)
print(cm)
fig = plt.figure()
fig.set_figheight(10)
fig.set_figwidth(10)
ax = fig.add_subplot()
cax = ax.matshow(cm)
plt.title('Confusion matrix of the classifier',pad=-570)
fig.colorbar(cax)
ax.set_xticklabels([''] + labels)
ax.set_yticklabels([''] + labels)
plt.setp(ax.get_xticklabels(), rotation=30, ha="left",
         rotation_mode="anchor")
plt.xlabel('Predicted')
plt.ylabel('True')
plt.show()

得到这个输出:

【问题讨论】:

    标签: python matplotlib data-visualization subplot confusion-matrix


    【解决方案1】:

    当您有多个类别时,matplotlib 将错误地标记轴。为了解决这个问题,您可以从 matplotlib.ticker 导入 MultipleLocator 来强制标记每个单元格。

    import matplotlib.pyplot as plt
    from matplotlib.ticker import MultipleLocator;
    
    # the same values in your confusion matrix
    labels = ['1','2','3','4','5','6','7','8','9','10','11','12']
    cm = [[0, 0, 61, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 1099, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 131, 23, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 36, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 40, 0, 0, 3, 0, 0, 0, 0, 0, 0],
        [0, 0, 43, 0, 0, 0, 31, 0, 0, 0, 0, 0],
        [0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 269, 0, 0, 0, 0, 0, 86, 0, 0, 6],
        [0, 0, 101, 0, 0, 0, 0, 0, 0, 45, 0, 1],
        [0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 283, 0, 0, 0, 0, 0, 0, 0, 0, 204]]
    
    fig = plt.figure()
    fig.set_figheight(10)
    fig.set_figwidth(10)
    ax = fig.add_subplot()
    cax = ax.matshow(cm)
    plt.title('Confusion matrix of the classifier',pad=-570)
    fig.colorbar(cax)
    
    ax.xaxis.set_major_locator(MultipleLocator(1))
    ax.yaxis.set_major_locator(MultipleLocator(1))
    
    ax.set_xticklabels([''] + labels)
    ax.set_yticklabels([''] + labels)
    plt.setp(ax.get_xticklabels(), rotation=30, ha="left",
             rotation_mode="anchor")
    plt.xlabel('Predicted')
    plt.ylabel('True')
    plt.show()
    

    【讨论】:

    • 很高兴听到!将来我可能会使用 seaborn 热图,但在 matplotlib 中了解这个 hack 并没有什么坏处
    • Matplotlib 不会错误地标记轴。它选择合理数量的刻度并显示这些刻度。想象一下你的矩阵是 10000x10000。你可能不想要 10000 个滴答声。
    猜你喜欢
    • 1970-01-01
    • 2021-08-15
    • 2013-10-14
    • 2021-01-17
    • 2023-03-20
    • 2011-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多