在Matplotlib中水平对齐两个Y轴的Y标签。

问题描述 投票:4回答:1

我想创建一个双轴图,在同一高度的轴顶上有y标签。

fig, ax = plt.subplots(1, 1)
ax.plot(data_left.index, data_left, label='Preis')
ax.set_ylabel('Preis', fontsize=label_size, rotation=0)
ax.yaxis.set_label_coords(0, 1.01)
ax2 = ax.twinx()
ax2.plot(data_right.index, data_right, label='KGV')
ax2.set_ylabel('KGV', fontsize=label_size, rotation=0)
ax2.yaxis.set_label_coords(1, 1.01)

所以我手动设置了两个轴的y标签coords高度为1.01,但是它们创建的位置完全不同。

enter image description here

当然,我可以在这些值上做文章,直到找到一个匹配的位置,但我想将这段代码用于不同的数据,并让标签自动放到正确的位置。

  • 为什么这些标签的y坐标完全不同?
  • 我如何对准它们的y坐标位置,使对准工作在任何数据集和标签上?
python matplotlib alignment axes
1个回答
3
投票

这和你想的一样 (rotation_mode=anchor + verticalalignment=baseline)

fig, ax = plt.subplots(1, 1)
ax.plot(data_left.index, data_left, label='Preis')
ax.set_ylabel('Preis', fontsize=20, rotation=0, rotation_mode="anchor", verticalalignment='baseline')
ax.yaxis.set_label_coords(0, 1.01)
ax2 = ax.twinx()
ax2.plot(data_right.index, data_right, label='KGV')
ax2.set_ylabel('KGV', fontsize=20, rotation=0, rotation_mode="anchor", verticalalignment='baseline')
ax2.yaxis.set_label_coords(1, 1.01)

问题是枢轴不在文本的中心,而是在Y轴上。

before rotation

after rotation

© www.soinside.com 2019 - 2024. All rights reserved.