使用matplotlib添加文本

使用matplotlib添加文本,matplotlib,text,Matplotlib,Text,我正在尝试使用matplotlib构建一个图形,但在图形本身上放置描述性文本时遇到问题 我的y值范围从.9到1.65,x值范围从日期2001到2021,并且来源于日期时间序列 以下是我工作的基本内容: fig, ax = plt.subplots(figsize=(10,7)) 我知道我必须使用ax.text()来放置任何文本,但每当我尝试为文本的x和y坐标输入基本上任何值时,当我重新运行单元格时,整个图形就会消失。我已经绘制了下面这条线,但是如果我在ax.text()中使用相同的坐标,我会得

我正在尝试使用matplotlib构建一个图形,但在图形本身上放置描述性文本时遇到问题

我的y值范围从
.9到1.65
,x值范围从日期
2001到2021
,并且来源于日期时间序列

以下是我工作的基本内容:

fig, ax = plt.subplots(figsize=(10,7))
我知道我必须使用
ax.text()
来放置任何文本,但每当我尝试为文本的x和y坐标输入基本上任何值时,当我重新运行单元格时,整个图形就会消失。我已经绘制了下面这条线,但是如果我在
ax.text()
中使用相同的坐标,我会得到刚才描述的输出。为什么会发生这种情况


plt.axhline(y=1.19,xmin=.032,xmax=.96)
默认情况下,
axhline
方法中的
y
参数位于数据坐标中,而
xmin
xmax
参数位于轴坐标中,其中
0
对应于绘图的最左侧,和
1
对应于绘图的最右侧。有关更多信息,请参阅

另一方面,在
text
方法中使用的
x
y
参数都位于数据坐标中,因此可以相对于数据定位文本。但是,可以使用
transform
参数将其更改为轴坐标。通过将其设置为
ax.transAxes
,实际上表明
x
y
参数应解释为轴坐标,同样
0
是绘图的最左侧(或底部),而
1
是绘图的最右侧(或顶部)。在这种情况下,您将使用
ax.text
,如下所示:

ax.text(x, y, 'text', transform=ax.transAxes)
有关更多信息,请参见

但是,听起来您可能希望结合数据和轴坐标来放置文本,因为您希望对文本重用
axhline
中的参数。在这种情况下,需要创建一个变换对象,将
x
坐标解释为轴坐标,将
y
坐标解释为数据坐标。这也可以通过创建混合变换来实现。例如:

import matplotlib.transforms as transforms

# create your ax object here

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

ax.text(x, y, 'text', transform=trans)
有关详细信息,请参见转换教程的一节

简而言之,您可以参考下图来比较这些不同转换的结果:

import matplotlib.pyplot as plt
import matplotlib.transforms as transforms

fig, ax = plt.subplots()

ax.set_xlim(0, 2)
ax.set_ylim(0, 2)

# note that the line is plotted at y=1.5, but between x=1.6 and x=1.8
# because xmin/xmax are in axis coordinates
ax.axhline(1.5, xmin=.8, xmax=.9)

# x and y are in data coordinates
ax.text(0.5, 0.5, 'A')

# here, x and y are in axis coordinates
ax.text(0.5, 0.5, 'B', transform=ax.transAxes)

trans = transforms.blended_transform_factory(x_transform=ax.transAxes, y_transform=ax.transData)
# here, x is in axis coordinates, but y is in data coordinates
ax.text(0.5, 0.5, 'C', transform=trans)