I'm trying to draw a line inside a scatterplot in matplotlib. I'm using an event function, so that images will be displayed when hovering over with the cursor. Now I want to draw a line between two specific points and display all images from scatter points crossed by line in a subplot next to scatter.
Is this possible and how can i achieve this?
Thanks for any help.
Following code is similar to previous posts here, but can't remember which. Changed some like from plot to scatter.
So far I'm using this code for displaying image on event:
def view_embedding_scatter(model, img_dim, root_path):
#data is generated from pytorch model
#images have a input dim of 128x128
#labelarr is feed bei DataLoader, represents classes
#x and y are reduced on dimensions by pca
#arr contains all images
# create figure and plot scatter
fig = plt.figure()
ax = fig.add_subplot()
sc = ax.scatter(x,y, c=labelarr, marker=".", linewidths=0.5, cmap="Dark2")
# create the annotations box
im = OffsetImage(arr[0,:,:], zoom=0.75)
xybox=(50., 50.)
ab = AnnotationBbox(im, (0,0), xybox=xybox, xycoords='data',
boxcoords="offset points", pad=0.3, arrowprops=dict(arrowstyle="->"))
# add it to the axes and make it invisible
ax.add_artist(ab)
ab.set_visible(False)
def hover(event):
# if the mouse is over the scatter points
if sc.contains(event)[0]:
# find out the index within the array from the event
ind, = sc.contains(event)[1]["ind"]
# get the figure size
w,h = fig.get_size_inches()*fig.dpi
ws = (event.x > w/2.)*-1 + (event.x <= w/2.)
hs = (event.y > h/2.)*-1 + (event.y <= h/2.)
# if event occurs in the top or right quadrant of the figure,
# change the annotation box position relative to mouse.
ab.xybox = (xybox[0]*ws, xybox[1]*hs)
# make annotation box visible
ab.set_visible(True)
# place it at the position of the hovered scatter point
ab.xy =(x[ind], y[ind])
# set the image corresponding to that point
im.set_data(arr[ind,:,:])
else:
#if the mouse is not over a scatter point
ab.set_visible(False)
fig.canvas.draw_idle()
# add callback for mouse moves
fig.canvas.mpl_connect('motion_notify_event', hover)
plt.tight_layout()
plt.show()