Matplotlib:带有 .get_window_extent() 的轴标签位置

Matplotlib: Axis label position with .get_window_extent()

我想在 yAxis 标签旁边添加带有 ax.text() 的文本。为此,我读出标签的位置并像这样转换它:

labelpos = ax.yaxis.label.get_window_extent()
box = labelpos.transformed(ax.transAxes.inverted())

为了控制位置,我使用 .patches 中的矩形,如下所示:

rect = Rectangle((box.xmin,box.ymin),box.width,box.height,
                  clip_on=False, fill=False, transform= ax.transAxes,ec='r', zorder=1000)
ax.add_patch(rect)

这是结果:

如您所见,位置并不总是正确的。看起来 ticklabel 宽度与它有关。我该如何补偿? 我试过使用 .get_ticklabel_extents,转换它并创建一个矩形:

extents1, extents2 = ax.yaxis.get_ticklabel_extents(renderer = fig.canvas.get_renderer())
box = extents2.transformed(ax.transAxes.inverted())

这是结果:

仍然,当刻度标签变长时,相同的偏移仍然存在。有什么想法吗?


编辑:

经过一些研究,我发现我的问题可能更深层次,因为 matplotlib.artist.Artist.get_window_extent 它说 from here:

Be careful when using this function, the results will not update if the artist window extent of the artist changes.

Soo...难道标签被艺术家移动了,无法读出当前位置?

解决方法: 使用 complex annotation 这样就可以将注释准确定位到轴标签:

                    an1 = par.annotate("text", xy=(0, 0), xycoords=ax.yaxis.label,
                                        xytext=(0, -20), textcoords="offset points",
                                         va="center", ha="left",rotation=90)

在这里回答:matplotlib Forum