0

Following this thread:

How to add hovering annotations to a plot

example.py

import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)

x = np.random.rand(15)
y = np.random.rand(15)
names = np.array(list("ABCDEFGHIJKLMNO"))
c = np.random.randint(1,5,size=15)

norm = plt.Normalize(1,4)
cmap = plt.cm.RdYlGn

fig,ax = plt.subplots()
sc = plt.scatter(x,y,c=c, s=100, cmap=cmap, norm=norm)

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

def update_annot(ind):
    
    pos = sc.get_offsets()[ind["ind"][0]]
    annot.xy = pos
    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)
    

def hover(event):
    vis = annot.get_visible()
    if event.inaxes == ax:
        cont, ind = sc.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()

fig.canvas.mpl_connect("motion_notify_event", hover)

plt.show()

I have managed to create a graph with points that when the mouse hovers it shows the point like this:

hover example

But when I tried to save it, the hovering option has gone. Based on the code(in the thread) I can only assume that it is interactive, the program should stay running for the hovering option to be displayed.

Is there a method that I can save the data for hovering options? Maybe even an online option that takes some sort of CSV or DataFrame.

linuxbeginner
  • 39
  • 1
  • 7
  • It would be helpful if you could share your code. Do you need it to be interactive? If not, check out the [annotations documentation for Matplotlib](https://matplotlib.org/stable/tutorials/text/annotations.html). – bc1155 Apr 14 '23 at 11:16
  • it's the same code from the thread... I do need it to be interactive, I have large data if the annotations will be shown in the picture they will cover the data itself, and I don't want that. – linuxbeginner Apr 14 '23 at 11:26
  • My point is that if you know which points you want to annotate, you can achieve that simply with another code block using minimal code from the documentation. If you need to keep it interactive because you’re annotating lots of specific points, then the solution will be more complex. – bc1155 Apr 14 '23 at 11:32
  • You can have interactive plots on a webpage via the plotly or bokey libraries. – JohanC Apr 14 '23 at 18:06
  • Do you have any references or some sort of guidelines? – linuxbeginner Apr 15 '23 at 07:40

0 Answers0