0

I'm tring to customize a code i found [here] (Possible to make labels appear when hovering over a point in matplotlib?) in order to create labels for points in a plot.

In the code snippet for using plot option they use the following line:

line, = plt.plot(x,y, marker="o")

After that the keep using the line variable in the rest of the code (for example):

def hover(event):
    vis = annot.get_visible()
    if event.inaxes == ax:
        cont, ind = line.contains(event)
        if cont:
            update_annot(ind)
            annot.set_visible(True)
            fig.canvas.draw_idle()
        else:
            if vis:
                annot.set_visible(False)
                fig.canvas.draw_idle()

In my code, i create plot of points instead of creating a line in the following way (i'm not using scatter because i need to create the points by their location - adjust the color and shape of the marker for that and i got a little confused with scatter for that):

    def create_plot(self):
        for s in self.soldiers:
            if s.company_number == 1:
                if type(s) == Soldier:
                    self.canvas.ax.plot(s.x, s.y, marker='o', markersize=5, color="blue", picker=5, label=s.__str__())
                else:
                    self.canvas.ax.plot(s.x, s.y, marker='*', markersize=5, color="blue", picker=5, label=s.__str__())

            elif s.company_number == 2:
                if type(s) == Soldier:
                    self.canvas.ax.plot(s.x, s.y, marker='o', markersize=5, color="red", picker=5, label=s.__str__())
                else:
                    self.canvas.ax.plot(s.x, s.y, marker='*', markersize=5, color="red", picker=5, label=s.__str__())

            elif s.company_number == 3:
                if type(s) == Soldier:
                    self.canvas.ax.plot(s.x, s.y, marker='o', markersize=5, color="green", picker=5, label=s.__str__())
                else:
                    self.canvas.ax.plot(s.x, s.y, marker='*', markersize=5, color="green", picker=5, label=s.__str__())
            else:
                continue

What should i change in the code in order to customize the line variable to my create_plot function?

Adi Portal
  • 55
  • 6
  • 1
    it's hard to tell you what to change without access to the complete code. Please take the time to produce a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) so that one can help out. At the minimum, you need to store a reference to the line somewhere `line, = self.canvas.ax.plot()` in a way that `hover()` can access that `line` object as well – Diziet Asahi Oct 03 '19 at 09:40
  • Instead of one line or scatter, here you have as many as there are "soldiers". So you will need to loop through those lines first to know if *any* of those lines is hit; and probably also to synchronize with the annotation you want to display. – ImportanceOfBeingErnest Oct 03 '19 at 13:22

0 Answers0