如何在 matplotlib 中将轴标签对齐到右侧或顶部?

新手上路,请多包涵

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

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

是否可以使用 matplotlib 的全局设置来实现?

原文由 Ruggero Turra 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.2k
2 个回答

v3.3 开始,您现在可以使用 loc 参数 set_xlabelset_ylabel

 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)

在此处输入图像描述在此处输入图像描述

原文由 iacob 发布,翻译遵循 CC BY-SA 4.0 许可协议

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

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

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

请注意,在这两种情况下,我们都将更改水平对齐方式,原因在我第一次更改 ylabel 中的垂直对齐方式时最终对我来说很清楚。

原文由 gboffi 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题