如何在Matplotlib 3D散点图中实现鼠标悬停显示数据点名称
Matplotlib 3D散点图添加鼠标悬停显示名称的简易方案
对于新手来说,原生Matplotlib的3D图悬停提示实现起来比较繁琐,用mplcursors库可以快速解决问题,步骤如下:
1. 安装依赖库
先在终端执行命令安装:
pip install mplcursors
2. 修改你的代码
替换为以下完整版本,关键改动已标注:
import matplotlib.pyplot as plt import mplcursors # 新增导入库 # 假设你的df已提前加载完成 z = df['est_diameter_max'] x = df['miss_distance'] y = df['relative_velocity'] n = df['name'] fig = plt.figure(figsize = (20,17)) ax = plt.axes(projection ="3d") ax.xaxis.set_pane_color((0.0, 0.0, 0.0, 0.0)) ax.yaxis.set_pane_color((0.0, 0.0, 0.0, 0.0)) ax.zaxis.set_pane_color((0.0, 0.0, 0.0, 0.0)) ax.xaxis.line.set_color("red") ax.yaxis.line.set_color("green") ax.zaxis.line.set_color("white") ax.tick_params(axis='x', colors='red') ax.tick_params(axis='y', colors='green') ax.tick_params(axis='z', colors='white') # 保存散点图对象(关键步骤) scatter = ax.scatter3D(x, y, z, color = "white") ax.set_facecolor("black") plt.title("Hazardous Near Earth Objects that Missed (2020-2022)", fontweight ='bold') ax.set_xlabel('Missed Distance in KM', fontweight ='bold', color='red') ax.set_ylabel('Velocity Relative to Earth', fontweight ='bold', color='green') ax.set_zlabel('Estimate Max Diameter in KM', fontweight ='bold', color='white') # 添加悬停提示核心逻辑 cursor = mplcursors.cursor(scatter, hover=True) @cursor.connect("add") def on_add(sel): # 通过索引获取对应名称 sel.annotation.set_text(n.iloc[sel.target.index]) # 适配黑色背景的提示框样式 sel.annotation.get_bbox_patch().set(fc="black", ec="white") sel.annotation.set_color("white") plt.show()
关键部分说明
scatter = ax.scatter3D(...):必须保存散点图的返回对象,让mplcursors能定位到要绑定的元素mplcursors.cursor(scatter, hover=True):创建悬停光标并绑定到散点图on_add函数:鼠标悬停时触发,通过sel.target.index获取当前点在DataFrame中的索引,取出对应名称作为提示文本- 最后几行调整提示框样式,适配你的黑色背景,让文字更清晰
修改完成后,运行代码鼠标悬停在任意白点上,即可显示对应的天体名称。
内容的提问来源于stack exchange,提问作者Nettle
相关产品推荐
相关产品推荐

