在子地块matplotlib中循环时文本和注释x和y坐标发生变化的问题

在子地块matplotlib中循环时文本和注释x和y坐标发生变化的问题,matplotlib,annotations,subplot,axes,Matplotlib,Annotations,Subplot,Axes,我想迭代子图,绘制数据,并使用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

我想迭代子图,绘制数据,并使用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实际上可能应用于fig的坐标,或者类似的东西。用我的实际数据来看,最终结果要糟糕得多!!!在这种情况下,某些注释最终位于实际绘图上方数英里处,甚至不在任何子绘图轴的坐标范围内。其他完全重叠!我在误解什么


有关详细信息,请编辑:

我已经尝试过Stef使用axes.text(0.1,0.1,'注释'…)的轴坐标的解决方案。

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

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


有关更多信息,请参阅。

那么matplotlib如何知道哪个是哪个?轴坐标是否仅在0和1之间,左下角为[0,0]?是的,请参阅链接教程中的表格Hank you-I错误编码了transform属性。修改后,我意识到我把Stef的解决方案错误地编码到了我的回复中。它确实起作用,正是transform=ax.transAxes设置例程来识别轴坐标而不是数据坐标。
ax.text(.1, .1, 'Annotation', color=annotation_colors[jj], transform=ax.transAxes)