python点击显示图片的程序,将鼠标悬停在一个点上时,Python显示图像

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 hover your mouse over each point? I tried plotly but found out you need to manually edit javascript to get the hover event to work. Is there a simple solution just with matplotlib or some other common package?

解决方案

Find here a complete solution on how to display an image on hover events. It uses a 'motion_notify_event' to detect when the mouse is over a scatter point (hovering). If this is the case, it displays an image annotation with a corresponding image next to the hovered scatter point.

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()

0102b27354536941ed34c5cea4d19fad.png

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 你可以使用 Python 的可视化库如 Matplotlib 或 Plotly 来绘制地图和图表。然后,使用交互工具如 ipywidgets 实现鼠标悬浮点击交互。 代码示例如下: ``` import plotly.express as px import pandas as pd from ipywidgets import interact df = pd.read_csv("data.csv") def show_graph(location): fig = px.scatter(df, x="Longitude", y="Latitude", color="Value", size="Value", hover_data=["Location"], height=600) fig.update_layout( title=location, xaxis_title="Longitude", yaxis_title="Latitude" ) fig.show() def show_table(location): df_location = df[df["Location"] == location] return df_location def on_click(trace, points, state): location = points.point_inds[0] show_table(df.iloc[location]["Location"]) def on_hover(trace, points, state): location = points.point_inds[0] show_graph(df.iloc[location]["Location"]) fig = px.scatter(df, x="Longitude", y="Latitude", color="Value", size="Value", hover_data=["Location"], height=600) fig.update_layout( xaxis_title="Longitude", yaxis_title="Latitude" ) fig.show() fig.data[0].on_click(on_click) fig.data[0].on_hover(on_hover) ``` 这段代码的做法是: - 使用 Plotly 绘制一个散点图,并在图中显示位置名称。 - 定义 on_click 函数,显示该位置的数据表。 - 定义 on_hover 函数,显示该位置的详细图表。 - 将 on_click 和 on_hover 函数附加到散点图数据上。 ### 回答2: 要实现在地图上使用Python编写一个点,当鼠标悬停在该点上时显示一张图,并在点击图时显示一张数据表,可以使用以下步骤: 首先,需要使用Python的数据可视化库,如Matplotlib或Plotly创建一个地图,并在地图上标记出需要的点。 接下来,使用鼠标事件监听器来监听鼠标的移动和点击事件。当鼠标悬停在点上时,触发一个函数,该函数将加载并显示所需的图表。 为了显示图表,可以选择使用计算机视觉库,如OpenCV,来加载和显示图像文件。使用OpenCV,你可以在鼠标悬停在点上时加载和显示图像。 当鼠标点击图像时,你可以使用Pandas库将数据加载到一个数据帧中,并使用一个表格显示数据。Pandas提供了一个简单易用的数据结构和数据分析工具,可以轻松地加载和处理各种数据。 最后,使用GUI库,如Tkinter或PyQt,创建一个用户界面,将地图和图表框放置在适当的位置。这样,当用户将鼠标悬停在点上时,图表框将显示在地图上,用户可以点击图表框,显示数据表。 通过上述步骤,你可以使用Python在地图上创建一个点,当鼠标悬停在该点上时显示一张图,并在点击图时显示一张数据表。 ### 回答3: 在Python中,可以使用第三方库folium实现在地图上显示点,并添加悬浮点击事件。 首先,需要安装folium库,可以使用pip命令进行安装。 通过以下代码可以实现在地图上显示一个点,并且在鼠标悬浮显示一张图: ```python import folium # 创建地图 m = folium.Map(location=[latitude, longitude]) # 创建一个标记点 tooltip = "悬浮显示的内容" marker = folium.Marker([latitude, longitude], popup='<img src="image.png">', tooltip=tooltip) # 添加标记点到地图上 marker.add_to(m) # 保存地图 m.save('map.html') ``` 其中,`latitude`和`longitude`是点的纬度和经度。 `<img src="image.png">`表示在悬浮显示图像,你需要将`image.png`替换为你要显示图像文件路径。 接下来,实现点击标记点时显示一张数据表: ```python import pandas as pd import folium # 创建地图 m = folium.Map(location=[latitude, longitude]) # 创建一个标记点 tooltip = "悬浮显示的内容" marker = folium.Marker([latitude, longitude], popup='<div id="myTable"></div>', tooltip=tooltip) # 添加标记点到地图上 marker.add_to(m) # 创建数据表并保存为HTML文件 data = {'Name': ['John', 'Mike', 'Sarah'], 'Age': [25, 30, 35]} df = pd.DataFrame(data) df.to_html('table.html', index=False) # 添加数据表到标记点的弹窗 m.get_root().html.add_child(folium.Element('<script>document.getElementById("myTable").innerHTML = `{}`;</script>'.format(df.to_html()))) # 保存地图 m.save('map.html') ``` 其中,`latitude`和`longitude`同样是点的纬度和经度。 `<div id="myTable"></div>`表示在点击显示的数据表,点击标记点后会在弹窗中显示。 `df = pd.DataFrame(data)`创建一个DataFrame数据表,你可以指定你自己的数据。 `df.to_html('table.html', index=False)`将数据表保存为HTML文件,命名为`table.html`。 `m.get_root().html.add_child(folium.Element('<script>document.getElementById("myTable").innerHTML = `{}`;</script>'.format(df.to_html())))`通过JavaScript将数据表添加到标记点的弹窗。 最后,通过`m.save('map.html')`保存地图为HTML文件,你可以在浏览器中打开该文件,即可看到地图和标记点。鼠标悬浮标记点时会显示一张图,点击标记点后会显示数据表。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值