【问题标题】:How to align axis label to the right or top in matplotlib?如何在 matplotlib 中将轴标签对齐到右侧或顶部?
【发布时间】:2016-07-04 13:34:27
【问题描述】:

默认情况下matplotlib 在轴的中心绘制轴标签。我想以这样的方式移动标签,使其与轴的末端对齐,无论是水平轴还是垂直轴。例如对于我想看到的水平轴:

+--------------------+
|                    |
|                    |
|                    |
|                    |
|                    |
+--------------------+
                 label

用matplotlib的全局设置可以吗?

【问题讨论】:

    标签: python matplotlib axis-labels


    【解决方案1】:

    我的另一个答案仍然是一个好答案,因为获取一个对象、修改它并将其重新设置回来的想法本身就是一个好主意,但这是一个替代的、更清洁的解决方案:

    ...
    plt.xlabel('x_description', horizontalalignment='right', x=1.0)
    plt.ylabel('y_description', horizontalalignment='right', y=1.0)
    ...
    

    如您所见,不再有幻数,并且适用于 xlabelylabel

    请注意,在这两种情况下,我们都将更改水平对齐方式,原因在我第一次更改 ylabel... 中的垂直对齐方式时我终于明白了。

    【讨论】:

    • 不能编辑,因为6个字符限制,应该有plt.xlabel('x description', horizontalalignment='right', x=1.0)
    • @anatol 交换 horizontalalignmentx/y(请在两个语句中)- 超过 6 个字符...感谢您发现我的错误!
    • 如果我将其更改为 horizontalalignment = 'left' 它会中断。你能解释一下这是如何工作的(即xy 参数是如何影响的)吗?
    • @Greenstick 恐怕我帮不上忙,因为差不多 5 年后我不再记得问题的细节了。此外,“它坏了” 并没有太大帮助……
    【解决方案2】:

    一个临时解决方案,它引入了我不太了解的神奇值25,至少可以说是

    plt.xlabel('pollo', horizontalalignment='right', position=(1,25))
    

    更明智的方法是使用 axes.xaxis 选择的任何 y 位置......考虑到这个想法,一个理智的过程通常就像

    1. 使用父容器的.get_object(...)方法获取对象
    2. 修改对象
    3. 使用其.set_object(...) 方法更新父级

    在我们的例子中,我们绘制绘图,然后我们得到当前轴 ax,其中包含 xaxis,其中包含要修改其位置和对齐方式的 label

    ...
    plt.xlabel('...')
    ...
    ax = plt.gca()
    label = ax.xaxis.get_label()
    x_lab_pos, y_lab_pos = label.get_position()
    label.set_position([1.0, y_lab_pos])
    label.set_horizontalalignment('right')
    ax.xaxis.set_label(label)
    ...
    plt.show()
    

    关于直接使用matplotlib 的默认值,我浏览了plt.rcParams 数据结构,但没有发现任何有用的信息。当然,这并不意味着不可能,只是我看不到可行的解决方案。

    【讨论】:

    • 我想知道是否可以通过 matplotlib 的全局设置来做到这一点
    【解决方案3】:

    v3.3 开始,您现在可以使用set_xlabelset_ylabelloc 参数设置这些:

    import matplotlib.pyplot as plt
    
    # Left plot
    options = ['left', 'center', 'right']
    fig, axs = plt.subplots(len(options), 1, constrained_layout=True)
    
    for ax, loc in zip(axs, options):
        ax.plot([1, 2, 3])
        ax.set_xlabel(f'xlabel loc={loc!r}', loc=loc)
    
    # Right plot
    options = ['bottom', 'center', 'top']
    fig, axs = plt.subplots(1, len(options), constrained_layout=True)
    
    for ax, loc in zip(axs, options):
        ax.plot([1, 2, 3])
        ax.set_ylabel(f'ylabel loc={loc!r}', loc=loc)
    

    【讨论】:

      猜你喜欢
      • 2021-10-29
      • 2016-09-26
      • 2020-05-11
      • 1970-01-01
      • 2014-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多