【问题标题】:Annotation alignment when interactively redrawing figure [duplicate]交互式重绘图形时的注释对齐[重复]
【发布时间】:2019-06-26 15:48:54
【问题描述】:

我从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")

...

产生以下输出:

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

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

【问题讨论】:

  • 基本上this answer 已经回答了这个问题。它会被视为重复吗?
  • 是的!我错过了这个答案。我应该删除它还是将其标记为重复会更好?
  • 标记为重复就好了;这增加了人们在搜索问题时找到答案的机会。

标签: python matplotlib


【解决方案1】:

仔细阅读文档,发现与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 参数,即箭头末端。此外,即使xytext 使用继承自 Text 实例方法 set_position 进行了修改,它仍以 textcoords 定义的单位进行解释(即使在这种情况下,textcoord 单位与 Text 实例不兼容)。

【讨论】:

    猜你喜欢
    • 2012-08-01
    • 1970-01-01
    • 2015-12-19
    • 1970-01-01
    • 1970-01-01
    • 2010-11-13
    • 2016-10-13
    • 2021-03-25
    • 2018-07-20
    相关资源
    最近更新 更多