0

I have a problem to align y axes labels when I add a second y axis. When I use command like bellow location of labels are not the same.

ax.set_ylabel('gram', fontsize='xx-small', rotation=0, loc="top")
ax2.set_ylabel('kg', fontsize='xx-small', rotation=0, loc="top")

How to fix it? output when I use loc='top' on both axes

I tried to use (alternatively to loc) va and ha text parameters, but this is not work correctly.

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
elephant69
  • 11
  • 1
  • What do you want your plot to look like? Where do you want to place the labels? – Simone Nov 19 '21 at 11:53
  • Does this answer your question? [How do I align gridlines for two y-axis scales using Matplotlib?](https://stackoverflow.com/questions/26752464/how-do-i-align-gridlines-for-two-y-axis-scales-using-matplotlib) – Trenton McKinney Nov 19 '21 at 13:57

1 Answers1

1

The vertical alignments are different in your example: Make them the same:

import matplotlib.pyplot as plt
fig,axs = plt.subplots(1, 2, constrained_layout=True, figsize=(5, 3))
ax = axs[0]
ax2 = ax.twinx()
ax.set_ylabel('gram', rotation=0, loc="top")
ax2.set_ylabel('kg', rotation=0, loc="top")
ax = axs[1]
ax2 = ax.twinx()
ax.set_ylabel('gram', rotation=0, loc="top", va='bottom')
ax2.set_ylabel('kg', rotation=0, loc="top", va='bottom')
plt.show()

enter image description here

Jody Klymak
  • 4,979
  • 2
  • 15
  • 31
  • thank you. it works, however I don't understand why va='bottom' effectively align to the top :) – elephant69 Nov 22 '21 at 08:37
  • `va` is the vertical alignment relative to the position of the label. So the label is put at `y=1.0` (in axes-relative co-ordinates) , and the text is then aligned with that: https://matplotlib.org/stable/tutorials/text/text_props.html – Jody Klymak Nov 22 '21 at 09:03