【问题标题】:Aligning rotated xticklabels and ylabels with their respective xticks and yticks将旋转 xticklabels 和 y 标签与其各自的 xticks 和 yticks 对齐
【发布时间】:2023-02-17 13:33:52
【问题描述】:

这是代码的输出:

array = [[64,7,5],
         [9,195,1],
         [6,17,2]]
df_cm = pd.DataFrame(array, range(3), range(3))

sn.set(font_scale=1.4) # for l)abel size

sn.heatmap(df_cm, annot=True, annot_kws={"size": 16}, cmap='Blues', fmt='g') # font size
class_names = ['dog','cat','bear']

plt.gca().xaxis.tick_top()
plt.gca().xaxis.set_label_position('top')
 
tick_marks = np.arange(len(class_names))
plt.xticks(tick_marks, class_names, rotation=45, rotation_mode='anchor')
plt.yticks(tick_marks, class_names, rotation='horizontal')# rotation='horizontal', ha='right', rotation_mode='anchor'
plt.tight_layout()
plt.ylabel('True label',size=14)
plt.xlabel('Predicted label',size=14)

plt.show()

我想将 x 和 y 的标签与中心位置对齐,请问如何更改以上内容

【问题讨论】:

    标签: python matplotlib axis-labels


    【解决方案1】:

    使用 tick_marks = np.arange(len(class_names)),您将设置新的刻度线。只需使用ax.get_xticks()/ax.get_yticks()获取现有的:

    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    import seaborn as sn
    
    array = [[64,7,5],
             [9,195,1],
             [6,17,2]]
    df_cm = pd.DataFrame(array, range(3), range(3))
    
    sn.set(font_scale=1.4) # for l)abel size
    
    fig, ax = plt.subplots()
    
    sn.heatmap(df_cm, annot_kws={"size": 16}, cmap='Blues', fmt='g') # font size
    class_names = ['dog','cat','bear']
    
    plt.gca().xaxis.tick_top()
    plt.gca().xaxis.set_label_position('top')
     
    plt.xticks(ax.get_xticks(), class_names, rotation=45, rotation_mode='anchor')
    plt.yticks(ax.get_yticks(), class_names, rotation='horizontal')# rotation='horizontal', ha='right', rotation_mode='anchor'
    plt.tight_layout()
    plt.ylabel('True label',size=14)
    plt.xlabel('Predicted label',size=14)
    
    plt.show()
    

    输出:

    编辑:通过将 plt.xticks(...)plt.yticks(...) 替换为以下内容,您将获得相同的结果:

    plt.gca().set_xticklabels(class_names, rotation=45, rotation_mode='anchor')
    plt.gca().set_yticklabels(class_names, rotation='horizontal')
    

    【讨论】:

      猜你喜欢
      • 2019-02-01
      • 2021-07-08
      • 2018-08-22
      • 2014-04-11
      • 1970-01-01
      • 1970-01-01
      • 2021-12-10
      • 1970-01-01
      相关资源
      最近更新 更多