Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python将鼠标悬停在点上时显示图像_Python_Matplotlib - Fatal编程技术网

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

Python将鼠标悬停在点上时显示图像,python,matplotlib,Python,Matplotlib,我有一个点的二维散点图,对应于图像。我想知道当你将鼠标悬停在每个点上时,是否有一种简单的方法来显示相应的图像(作为弹出窗口或工具提示)?我尝试过,但发现需要手动编辑javascript才能使悬停事件正常工作。仅使用matplotlib或其他常见软件包是否有一个简单的解决方案?在此处找到有关如何在悬停事件上显示图像的完整解决方案。它使用一个“运动通知事件”来检测鼠标何时在分散点上(悬停)。如果是这种情况,则会在悬停的散射点旁边显示一个带有相应图像的 import matplotlib.pyplot

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

在此处找到有关如何在悬停事件上显示图像的完整解决方案。它使用一个
“运动通知事件”
来检测鼠标何时在分散点上(悬停)。如果是这种情况,则会在悬停的散射点旁边显示一个带有相应图像的

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()
导入matplotlib.pyplot作为plt
从matplotlib.offsetbox导入OffsetImage、AnnotationBbox
输入numpy作为np;np.随机种子(42)
#为散射和图像阵列生成数据x、y。
x=np.arange(20)
y=np.rand.rand(len(x))
arr=np.空((len(x),10,10))
对于范围内的i(len(x)):
f=np.rand.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)
#创建图形并绘制散点
图=plt.图()
ax=图添加_子批次(111)
直线,=ax.绘图(x,y,ls=”“,marker=“o”)
#创建注释框
im=OffsetImage(arr[0,:,:],zoom=5)
xybox=(50,50.)
ab=注释bbox(im,(0,0),xybox=xybox,xycoords='data',
boxcoords=“偏移点”,pad=0.3,arrowprops=dict(arrowstyle=“->”)
#将其添加到轴并使其不可见
ax.添加艺术家(ab)
ab.set_可见(假)
def悬停(事件):
#如果鼠标位于散射点上方
如果行包含(事件)[0]:
#从事件中找出数组中的索引
ind,=line.contains(事件)[1][“ind”]
#获取数字大小
w、 h=图尺寸英寸()*图dpi

ws=(event.x>w/2。)*-1+(event.x h/2。)*-1+(event.y如果您希望图像以RGB显示,则必须稍微调整代码。对于本例,图像需要位于磁盘上。您需要使用plt.imread读取图像,然后将_数据设置到图像中的相应位置,而不是使用三维数组来处理第一个维度仅表示索引的图像包含图像名称的数组

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('<U12') # names of your images files

cmap = plt.cm.RdYlGn

# create figure and plot scatter
fig = plt.figure()
ax = fig.add_subplot(111)
#line, = ax.plot(x,y, ls="", marker="o")
line = plt.scatter(x,y,c=heat, s=10, cmap=cmap)
image_path = np.asarray(jpg_name_np)

# create the annotations box
image = plt.imread(image_path[0])
im = OffsetImage(image, zoom=0.1)
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(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()
导入matplotlib.pyplot作为plt
从matplotlib.offsetbox导入OffsetImage、AnnotationBbox
导入numpy作为np;np.random.seed(42)
导入操作系统
chdir('Path/to/your/images')
#为散射和图像阵列生成数据x、y。
x=np.arange(3)
y=np.rand.rand(len(x))

jpg_name_np=np.array(['904646.jpg','903825.jpg','905722.jpg']).astype(“可能重复@fuglede:看起来这个解决方案涉及单击,而我更喜欢悬停。不幸的是,第二个悬停的答案在jupyter中似乎不起作用。我想你需要
运动通知事件
:第一个解决方案是关于单击,但另一个解决悬停。在jupyter笔记本中,它是c我们最好启用
%matplotlib笔记本
后端。否则无法进行交互。是否可以使用不同的数据组执行相同的操作。例如,假设有3个类别,您需要在此处执行for循环ie。每个x,y数据点是否仍能显示代表性图像?谢谢,抱歉,我通过这些数据点使用alpha 0透明并覆盖彩色绘图。请告诉我是否有更正确的方法作为独立脚本可以正常工作,但不适用于Colab(使用
%matplotlib inline
%matplotlib notebook
):没有图像显示这对我来说在Colab上不起作用。(即使在更改路径并将其指向图像之后)