ax.text 对 (x,y) 使用组合的 transData 和 transAxes

ax.text using combined transData and transAxes for (x,y)

我正在尝试在同一张图中打印一组线条,并在轴的顶部,每行上方写一些文本。我用每组数据的x的最小值作为文本的位置。代码看起来像

for i in range(jobs):
  ax.text(xmin,1.15, nameid, rotation=45, ha='left', fontsize=tinyfont, color='k', va='center')

当我做类似的事情时,文本被打印出来了——但是在图表的中间(因为它使用的是数据坐标):

因为我想在轴上方打印,所以我用然后transform=ax.transAxes在上面打印,as

for i in range(jobs):
  ax.text(xmin,1.15, nameid, transform=ax.transAxes, rotation=45, ha='left', fontsize=tinyfont, color='k', va='center')

虽然文字移到了正确的位置,但只写了第一个:

编辑:发生这种情况是因为位置高于轴限制 1.0。所以,对于 x 位置,我想使用数据值 xmin;对于 y,我想要轴上方的固定位置。问题是我事先不知道最后的 x_lim 和 y_lim,因为我遍历数据并绘制不同的部分。

如何使用数据的 x 添加文本,但在轴上方的常量“y”中?

您想使用“混合变换”,其中您使用数据坐标作为 x 轴,轴坐标作为 y 轴。这记录在这里:

https://matplotlib.org/stable/tutorials/advanced/transforms_tutorial.html#blended-transformations

一个简单的例子是:

import matplotlib.transforms as transforms

fig, ax = plt.subplots()

trans = transforms.blended_transform_factory(ax.transData, ax.transAxes)

# code to plot, and find xmin, etc...

ax.text(xmin, 1.15, nameid, rotation=45, ha='left', fontsize=tinyfont,
        color='k', va='center', transform=trans) 

请注意,在文档站点上,它提到了一个快捷方式:

The blended transformations where x is in data coords and y in axes coordinates is so useful that we have helper methods to return the versions Matplotlib uses internally for drawing ticks, ticklabels, etc. The methods are matplotlib.axes.Axes.get_xaxis_transform() and matplotlib.axes.Axes.get_yaxis_transform(). So in the example above, the call to blended_transform_factory() can be replaced by get_xaxis_transform:

trans = ax.get_xaxis_transform()

因此,您可以使用:

ax.text(xmin, 1.15, nameid, rotation=45, ha='left', fontsize=tinyfont,
        color='k', va='center', transform=ax.get_xaxis_transform())