Python 在将鼠标悬停在一个点上时显示图像

标签 python matplotlib

我有一个二维散点图,对应于图像。我想知道当您将鼠标悬停在每个点上时是否有一种简单的方法来显示相应的图像(作为弹出窗口或工具提示)?我有意地尝试过,但发现您需要手动编辑 javascript 才能使悬停事件正常工作。是否有仅使用 matplotlib 或其他一些常见软件包的简单解决方案?

最佳答案

在此处找到有关如何在悬停事件中显示图像的完整解决方案。它使用 'motion_notify_event' 来检测鼠标何时位于分散点(悬停)上。如果是这种情况,它会显示 image annotation。在悬停的散点旁边有一个相应的图像。

import matplotlib.pyplot as plt
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
import numpy as np; np.random.seed(42)

# Generate data x, y for scatter and an array of images.
x = np.arange(20)
y = np.random.rand(len(x))
arr = np.empty((len(x),10,10))
for i in range(len(x)):
    f = np.random.rand(5,5)
    arr[i, 0:5,0:5] = f
    arr[i, 5:,0:5] =np.flipud(f)
    arr[i, 5:,5:] =np.fliplr(np.flipud(f))
    arr[i, 0:5:,5:] = np.fliplr(f)

# create figure and plot scatter
fig = plt.figure()
ax = fig.add_subplot(111)
line, = ax.plot(x,y, ls="", marker="o")

# create the annotations box
im = OffsetImage(arr[0,:,:], zoom=5)
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 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(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.show()

enter image description here

关于Python 在将鼠标悬停在一个点上时显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42867400/

相关文章:

python - 仅通过B表的插入操作更新A表的字段

python - Pandas 和 matplotlib : Combine two plots into one legend item

python - 如何格式化数据以供 seaborn 使用

每个句柄具有不同数量和颜色标记的 Matplotlib 图例

python - 如何安装 six.moves.xmlrpc_client?

python - 将数据写入 csv 不起作用

python - 将 pandas.Series.value_counts 返回的系列转换为字典

python - 是否可以禁用跳转到列表末尾?

python - 使用 matplotlib 删除散点图中的点

python - 在 matplotlib 中绘制 Pandas 日期