【问题标题】:Question regarding horizontal text alignment in a subplot with matplotlib关于 matplotlib 子图中水平文本对齐的问题
【发布时间】:2020-09-02 08:20:25
【问题描述】:

我无法在 matplotlib 的子图中对齐我的图例标签。我尝试了一种解决方法,其中涉及通过 ljust 函数填充标签,但是由于某种原因,它不能很好地转移到图例本身。下面是一些示例代码,其中包含用于复制我的问题的生成数据。

我正在尝试让标签文本像打印的语句一样对齐。

labellist = ['LR','XGB','SVM','LASSO']
fig, axs = plt.subplots(1, 1,figsize=(10,5))
fig.suptitle('ROC curves of the ML algorithms')
axs.set_title('ROC curve test set')
axs.set(xlabel="1 - Specificity", ylabel='Sensitivity')
axs.axis([-0.005, 1, 0, 1.005])

for i,item in enumerate(labellist):
    x = np.linspace(0, np.pi, 100)
    item_label = item.ljust(5) +" (auc: " +str(i)+ ')'
    axs.plot(x, np.cos(x*i), linewidth=1.5, label=item_label)
    print(item_label)
axs.legend()

有没有人可以解决这个问题?

【问题讨论】:

    标签: python matplotlib legend


    【解决方案1】:

    我在Text alignment in a Matplotlib legend找到了答案

    添加以下代码后,它运行良好。

    legend = axs.legend()
    renderer = fig.canvas.get_renderer()
    shift = max([t.get_window_extent(renderer).width for t in legend.get_texts()])
    for t in legend.get_texts():
        t.set_ha('right') # ha is alias for horizontalalignment
        t.set_position((shift,0))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-08
      • 2020-10-22
      • 2015-07-22
      • 1970-01-01
      • 1970-01-01
      • 2023-02-24
      • 2013-08-14
      • 1970-01-01
      相关资源
      最近更新 更多