循环遍历子图 matplotlib 时文本和注释 x 和 y 坐标发生变化的问题

Problem with text and annotation x and y coordinates changing while looping through subplots matplotlib

我想遍历子图、绘图数据,并使用 matplotlib 中的 text 函数或 annotation 函数对子图进行注释。这两个函数都需要 x 和 y 坐标以放置文本或注释。在我绘制数据之前,我可以让它正常工作。然后注释和文字就乱跳了,搞不懂为什么。

我的设置是这样的,它生成没有数据的对齐良好的注释:

import pandas as pd 
import matplotlib.pyplot as plt
import numpy as np 

fig, ax=plt.subplots(nrows=3, ncols=3, sharex=True)
fig.suptitle('Axes ylim unpacking error demonstration')
annotation_colors=["red", "lightblue", "tan", "purple", "lightgreen", "black", "pink", "blue", "magenta"]

for jj, ax in enumerate(ax.flat):
    bott, top = plt.ylim()
    left, right = plt.xlim()
    ax.text(left+0.1*(right-left), bott+0.1*(top-bott), 'Annotation', color=annotation_colors[jj])

plt.show

当我添加随机数据(或我的真实数据)时,注释跳转:

import pandas as pd 
import matplotlib.pyplot as plt
import numpy as np 

#Same as above but but with 9 random data frames plotted.
df_cols = ['y' + str(x) for x in range(1,10)]
df=pd.DataFrame(np.random.randint(0,10, size=(10,9)), columns=df_cols)
df['x']=range(0,10)

#Make a few columns much larger in terms of magnitude of mean values
df['y2']=df['y2']*-555
df['y5']=df['y5']*123

fig, ax=plt.subplots(nrows=3, ncols=3, sharex=True)
fig.suptitle('Axes ylim unpacking error demonstration')
annotation_colors=["red", "lightblue", "tan", "purple", "lightgreen", "black", "pink", "blue", "magenta"]

for jj, ax in enumerate(ax.flat):
    ax.plot(df['x'], df['y'+str(jj+1)], color=annotation_colors[jj])
    bott, top = plt.ylim()
    left, right = plt.xlim()
    ax.text(left+0.1*(right-left), bott+0.1*(top-bott), 'Annotation', color=annotation_colors[jj])

plt.show()

这只是为了演示可能由于我不了解 ax 和 fig 调用的工作原理而导致的问题。在我看来, ax.text 调用的坐标 x 和 y 实际上可能适用于无花果的坐标或类似的东西。最终结果比我的实际数据差得多!!!在那种情况下,一些注释最终会超出实际图数英里,甚至不在任何子图轴的坐标内。其他完全重叠!我误会了什么?


编辑更多详情:

我试过 Stef 的解决方案,使用 axes.text(0.1, 0.1, 'Annotation'...)

的轴坐标

我得到了下面的图,它仍然显示了将文本到处移动的相同问题。因为我 运行 这个例子是随机数,注释随每个 运行 随机移动——也就是说,它们不只是在具有不同轴范围(y2 和 y5)的子图中移位。

您可以在坐标轴坐标中指定文本位置(与您隐式执行的数据坐标相反):

ax.text(.1, .1, 'Annotation', color=annotation_colors[jj], transform=ax.transAxes)

有关详细信息,请参阅 Transformations Tutorial