You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

散点图鼠标悬停时显示对应数据名称的问题求助

解决散点图悬停显示对应名称的问题

问题核心在于sel.target.index返回的是单个散点图内部的点索引(仅0或1),而非原始数据的行索引,导致无法正确匹配names中的对应名称。你可以通过当前悬停的散点图对象来定位它在数据中的行位置,从而获取正确名称。

修改后的完整代码(基础实现)

import matplotlib.pyplot as plt
import mplcursors

data = [
    ["Name1", 10, 20],
    ["Name2", 30, 40],
    ["Name3", 50, 60]
]

x_values = ["G1", "G2"]
y_values = [(row[1], row[2]) for row in data]
names = [row[0] for row in data]

fig, ax = plt.subplots()

scatter_plots = []

for i in range(len(data)):
    scatter = ax.scatter(x_values, y_values[i])
    scatter_plots.append(scatter)

ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.set_title("Scatter Plot")

cursor = mplcursors.cursor(scatter_plots, hover=True)
# 通过sel.artist获取当前悬停的散点图,再匹配其在列表中的索引来获取名称
cursor.connect("add", lambda sel: sel.annotation.set_text(names[scatter_plots.index(sel.artist)]))

plt.show()

更高效的优化实现

如果数据量较大,list.index()会有性能损耗,你可以在创建散点图时直接给对象绑定对应名称:

import matplotlib.pyplot as plt
import mplcursors

data = [
    ["Name1", 10, 20],
    ["Name2", 30, 40],
    ["Name3", 50, 60]
]

x_values = ["G1", "G2"]

fig, ax = plt.subplots()

scatter_plots = []

# 直接解构数据,给每个散点图对象绑定名称属性
for name, y1, y2 in data:
    scatter = ax.scatter(x_values, [y1, y2])
    scatter.name = name
    scatter_plots.append(scatter)

ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.set_title("Scatter Plot")

cursor = mplcursors.cursor(scatter_plots, hover=True)
# 直接读取绑定的名称属性
cursor.connect("add", lambda sel: sel.annotation.set_text(sel.artist.name))

plt.show()

两种方法都能实现每组散点悬停时显示对应正确名称,第二种方式更直观且性能更优。

内容的提问来源于stack exchange,提问作者Vito

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 19:12:38