matplotlib:使用转换在子图中自动对齐yaxis的标签

时间:2015-06-30 08:40:36

标签: python matplotlib

我想像example这样对齐我的y轴标签。但是,我不想使用像ax4.yaxis.set_label_coords(labelx, 0.5)这样的固定值,而是使用类似的东西:

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

下标签的位置是“正确的”。我想确定它的x坐标并将其应用于上标签。我该怎么做?

我尝试了不同的变体:

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

但这并没有导致解决方案。

1 个答案:

答案 0 :(得分: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()...