将文本锚定或锁定到 Matplotlib 中的标记

Rah*_*Rah 5 python text annotate matplotlib marker

有什么方法可以将文本锚定或锁定到标记吗?当使用 提供的交互式缩放时pyplot,文本会超出范围,如图所示。

import matplotlib.pyplot as plt

x=[2,4]
y=[2,3]

fig, ax = plt.subplots()
ax.plot(x, y, 'ro',markersize=23)

offset = 1.0 
ax.set_xlim(min(x)-offset, max(x)+ offset)
ax.set_ylim(min(y)-offset, max(y)+ offset)

for x,y in zip(x,y):
     ax.annotate(str(y),  xy=(x-0.028,y-0.028))

plt.show()
Run Code Online (Sandbox Code Playgroud)

文字超出范围

sna*_*mer 4

简单的答案是它是默认完成的。文本的左下角与 指定的位置相关联xy。现在,如下图所示,当您以交互方式缩放到其中一个标记时,标记和文本的相对位置将被保留。

import matplotlib.pyplot as plt

x=[2,4]
y=[2,3]

fig, ax = plt.subplots()
ax.plot(x, y, 'ro',markersize=23)

offset = 1.0 
ax.set_xlim(min(x)-offset, max(x)+ offset)
ax.set_ylim(min(y)-offset, max(y)+ offset)

for x,y in zip(x,y):
     ax.annotate(str(y),  xy=(x,y))

plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述 在此输入图像描述

然而,这看起来相当难看,因为文本现在位于标记的右上象限,有时甚至位于标记的边缘上方。我想这就是您在 中添加 0.028 偏移量的原因xy=(x-0.028,y-0.028),因此引入了您现在试图摆脱的行为。发生的情况是,默认情况下matplotlib使用数据的坐标系来定位文本。当您缩放时,0.028 个数据单位表示帧的比例不断增加,并且文本“偏离”标记,最终结束在可见值范围之外。

要消除这种行为,您需要更改坐标系。该annotate参数textcoords可以设置为offset point。您可以在此处xytext指定距该位置的偏移量(以磅为单位)xy

ax.annotate(str(y),  xy=(x,y), xytext=(-5.0,-5.0), textcoords='offset points')
Run Code Online (Sandbox Code Playgroud)

现在,具有挑战性的部分是评估要添加到绘图中的文本的大小,以确定偏移值。文本可能会发生变化,但在绘制之前无法确定渲染文本字符串的大小。请参阅有关此事的这篇文章。在下面的示例代码中,我尝试引入一些灵活性:

import matplotlib.pyplot as plt

x=[2,4]
y=[2,12]

fig, ax = plt.subplots()
ax.plot(x, y, 'ro',markersize=23)

offset = 1.0 
ax.set_xlim(min(x)-offset, max(x)+ offset)
ax.set_ylim(min(y)-offset, max(y)+ offset)

for x,y in zip(x,y):
    text = str(y)
    fontsize, aspect_ratio = (12, 0.5) # needs to be adapted to font
    width = len(text) * aspect_ratio * fontsize 
    height = fontsize
    a = ax.annotate(text,  xy=(x,y), xytext=(-width/2.0,-height/2.0), textcoords='offset points')

plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

在这里,文本是长度为 2 的字符串,尽管进行了大量缩放,但它仍然大致以标记为中心。然而,您需要使该解决方案适应您的字体和字体大小。非常欢迎提出改进建议。