matplotlib: autoalign labels of yaxis in subplots using a transform

别等时光非礼了梦想. 提交于 2021-02-10 20:27:26

问题


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.


回答1:


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()...



来源:https://stackoverflow.com/questions/31133491/matplotlib-autoalign-labels-of-yaxis-in-subplots-using-a-transform

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!