Python show image upon hovering over a point

后端 未结 2 1293
名媛妹妹
名媛妹妹 2020-12-13 01:40

I have a 2-d scatter plot of points, that correspond to images. I was wondering if there\'s an easy way to display the corresponding image (as a popup or tooltip) when you h

2条回答
  •  半阙折子戏
    2020-12-13 02:20

    If you want your images to be displayed in RGB, you have to slightly adjust the code. For this example the images need to be at your disk. Instead of using an 3darray for the images where the first dimension only represents the index you need to read the image with the plt.imread and then set_data to the corresponding position in your array containing the image names.

    import matplotlib.pyplot as plt
    from matplotlib.offsetbox import OffsetImage, AnnotationBbox
    import numpy as np; np.random.seed(42)
    import os
    
    os.chdir('Path/to/your/images')
    
    # Generate data x, y for scatter and an array of images.
    x = np.arange(3)
    y = np.random.rand(len(x))
    jpg_name_np = np.array(['904646.jpg', '903825.jpg', '905722.jpg']).astype('"))
    # 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 line.contains(event)[0]:
            # find out the index within the array from the event
            ind, = line.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(plt.imread(image_path[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)  
    
    fig = plt.gcf()
    fig.set_size_inches(10.5, 9.5)
    
    plt.show()
    

    Plot when hovering over scatterpoint

提交回复
热议问题