Search code examples
pythonmatplotlibalignmentaxes

Horizontally Align Y Labels of Two Y Axis in Matplotlib


I am trying to create a dual axis plot with y labels on the top of the axis on the same height

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)

So I manually set the y label coords height to 1.01 for both axis but they are created in completely different places.

enter image description here

Of course I could play around with the values until I find a matching position, but I want to use this code for different data and have the labels automatically put to the right place.

  • Why are those labels on completely different y coordinates?
  • How do I align their y position, so that the alignment works for any dataset and label?

Solution

  • This works as you intended (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)
    

    The issue was the pivot not being at the center of the text but on the yaxis

    before rotation

    after rotation