1

I want to align my y-axis labels like in this example. However, I don't want to use a fixed value like ax4.yaxis.set_label_coords(labelx, 0.5), but rather something like this:

x = np.linspace(-np.pi, np.pi, 100)
y1 = np.sin(x)**2
y2 = np.sin(x)

fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)

ax1.plot(x, y1)
ax2.plot(x, y2)

ax1.set_ylabel('y1')
ax2.set_ylabel('y2') 

enter image description here

The position of the lower label is "correct". I want to determine its x-coordinate and apply it to the upper label. How do I do this?

I tried different variations of:

transform = ax2.yaxis.get_transform()
ax1.yaxis.set_transform(transform)

But that didn't lead to a solution.

Ohjeah
  • 1,269
  • 18
  • 24

1 Answers1

0

it seems you can a form of labelx from ax1.yaxis.get_label().get_position() but only after the axis has been drawn (as it is positioned based on the location of the label ticks, see @Matthias123 answer to this question). I assume that the matplotlib example specify a constant (and consistent) position because it is not trivial to get this dynamically. It also seems a much more robust way to work, instead of matching to whichever axis is furthest out.

If you do want to do this, I think you will need to convert the position from ax1.yaxis.get_label().get_position() which is apparently in pixels and then use ax1.yaxis.label.set_position()...

Community
  • 1
  • 1
Ed Smith
  • 12,716
  • 2
  • 43
  • 55
  • the point is to set it dynamically, because for each kind of value format on the yaxis one has to find that constant. I tried to use get position and set position but get position returns 0,0.5 for both ax1 and ax2. So I guess I will have to use the transforms somehow. – Ohjeah Jul 01 '15 at 07:56
  • If you call `plt.draw` first, then `get_position` returns something like `(40., 0.5)` for the label (no longer zero because I think it needs the ticks drawn before placing). Sorry, couldn't figure out a way to use this, think you need a transform like you said. No chance you could use `ax1.xaxis.labelpad`, perhaps iteratively until get position agree? – Ed Smith Jul 01 '15 at 10:50