我从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")
...
这将产生以下输出:
还有两个例子here和here。这不是预期的输出。箭头方向正确,文本接近所需的方向,但它与数据点对齐,而不是与箭头末端对齐
我期望得到的是在调用ax.annotate
(无需交互修改注释)时使用相同的参数实现的结果,这是以下行为:
仔细阅读文档,结果发现与
xy
不同,xytext
不是Annotation
对象的属性。因此,这条线实际上是在创建一个无用的属性。因此,文本位置没有从原始
(0,0)
偏移量修改。要实际修改文本位置,必须使用set_position()
:尽管我已经解决了这个问题,但我还是决定把这个问题贴出来,因为我发现它非常违反直觉,而且有点混乱
annot.xy
修改xy
参数,该参数是箭头位置的开头,annot.set_position
修改xytext
参数,该参数是箭头位置的结尾。此外,即使使用继承自文本实例的方法set_position
修改了xytext
,也会用textcoords
定义的单元来解释它(即使在这种情况下,textcoord
单元与文本实例不兼容)相关问题 更多 >
编程相关推荐