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

时间:2020-05-17 10:49:16

标签: python matplotlib alignment axes

我正在尝试创建一个具有相同高度的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标签坐标高度手动设置为1.01,但是它们是在完全不同的位置创建的。

enter image description here

当然,我可以一直使用这些值,直到找到匹配的位置,但是我想将此代码用于不同的数据并自动将标签放置在正确的位置。

  • 为什么这些标签在完全不同的y坐标上?
  • 如何对齐他们的y位置,以便对齐适用于任何数据集和标签?

1 个答案:

答案 0 :(得分:2)

这按预期工作(rotation_mode =锚点+ verticalalignment =基线)

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)

问题在于枢轴不在文本中心,而是在yaxis上

before rotation

after rotation