交互重画figu时的注释对齐

2024-06-26 13:23:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我从this other answer中的代码开始,修改了其中的一部分,以便在朝向绘图中心悬停时始终显示标签:

...

annot = ax.annotate("", xy=(0,0), xytext=(0,0),textcoords="offset points",
                    bbox=dict(boxstyle="round", fc="w"),
                    arrowprops=dict(arrowstyle="->"))
annot.set_visible(False)
xmid = np.mean(ax.get_xlim())                                                 
ymid = np.mean(ax.get_ylim())
offset = 20

def update_annot(ind):

    pos = sc.get_offsets()[ind["ind"][0]]
    annot.xy = pos
    annot.xytext = (-offset if pos[0] > xmid else offset, 
                    -offset if pos[1] > ymid else offset)
    text = "    {}, {}    ".format(" ".join(list(map(str,ind["ind"]))), 
                           " ".join([names[n] for n in ind["ind"]]))
    annot.set_text(text)
    annot.get_bbox_patch().set_facecolor(cmap(norm(c[ind["ind"][0]])))
    annot.get_bbox_patch().set_alpha(0.4)
    annot.set_ha("right" if pos[0] > xmid else "left")
    annot.set_va("top" if pos[1] > ymid else "bottom")

...

这将产生以下输出:

bad1

还有两个例子herehere。这不是预期的输出。箭头方向正确,文本接近所需的方向,但它与数据点对齐,而不是与箭头末端对齐

我期望得到的是在调用ax.annotate(无需交互修改注释)时使用相同的参数实现的结果,这是以下行为:

enter image description here


Tags: textposgetifaxelseoffsetxy
1条回答
网友
1楼 · 发布于 2024-06-26 13:23:40

仔细阅读文档,结果发现与xy不同,xytext不是Annotation对象的属性。因此,这条线

annot.xytext = (-offset if pos[0] > xmid else offset, 
                -offset if pos[1] > ymid else offset)

实际上是在创建一个无用的属性。因此,文本位置没有从原始(0,0)偏移量修改。要实际修改文本位置,必须使用set_position()

annot.set_position((-offset if pos[0] > xmid else offset, 
                    -offset if pos[1] > ymid else offset))

尽管我已经解决了这个问题,但我还是决定把这个问题贴出来,因为我发现它非常违反直觉,而且有点混乱annot.xy修改xy参数,该参数是箭头位置的开头,annot.set_position修改xytext参数,该参数是箭头位置的结尾。此外,即使使用继承自文本实例的方法set_position修改了xytext,也会用textcoords定义的单元来解释它(即使在这种情况下,textcoord单元与文本实例不兼容)

相关问题 更多 >