首页 > 解决方案 > 注释仅适用于最后绘制的线

问题描述

我已经获得了在给定图上绘制多条线的现有代码。代码很长,所以我只会发布我编写的代码并希望足够。我编写的代码是基于我在这里找到的代码构建的:当鼠标悬停在 matplotlib 中的某个点上时可能使标签出现?

问题是它只会在打印在多行图形上的最后一行上打印注释(我还打印出一个图例,它是该图例列表中的最后一个)。

我放置了几个打印语句,您可以在下面的代码中看到它们。在有条件的情况下,hit我将标签打印到控制台,当我从一行移动到另一行并在控制台中完美运行时,这会发生变化。接下来你会注意到我调用了这个update_annot函数。在这个函数中,我打印出另一个语句来验证我在函数中。控制台显示,每次我将鼠标悬停在一行上时,它实际上是进入了函数;但是,注释框不显示,除了一行。下面是我的代码。第一个片段是使用现有函数调用的,plotData.

annot = ax.annotate("", xy=(-20,20), xytext=(None),textcoords="offset 
                    points",
                    bbox=dict(fc="b"),
                    arrowprops=dict(arrowstyle="->"))
annot.set_visible(True)
h = lambda x: self.hover(x, ax, annot)
fig.canvas.mpl_connect("motion_notify_event", h)

#

def update_annot(self, annot, label, ind, x, y):
    print ("Entered update annot")
    annot.xy = (x[ind["ind"][0]], y[ind["ind"][0]])
    annot.set_text(label)
    annot.get_bbox_patch().set_alpha(0.4)
#end of update_annot



def hover(self, event, ax, annot):
    #if event.inaxes == ax:
    for curve in ax.get_lines():
        label = curve.get_label()
        x,y = curve.get_data()
        hit, ind = curve.contains(event)

        if hit:
            print(label)
            self.update_annot(annot, label, ind, x, y)
            annot.set_visible(True)
            plt.draw()
        else:
            annot.set_visible(False)
            plt.draw()

我希望看到注释框出现在每一行;但相反,它只显示在打印的一行中。这让我很困惑,因为它每次输入条件时都会在控制台上正确打印标签,并且每次hit它也会进入更新功能。我对 Python 真的很陌生,所以如果我的代码中有任何建议(即使是在问题之外),我很想听听。另外,正如我所指出的,我正在构建我在这里找到的代码。我仍然不确定annot.xy它的作用,因为在xy定义时annot已经定义了。先感谢您。

标签: pythonmatplotlib

解决方案


推荐阅读