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

如何调整mplcursors交互规则,仅响应散点及误差棒端点隐藏散点

带误差棒散点图交互功能优化方案

原代码需完成两处调整:

  • 限制mplcursors仅响应散点(含误差棒上下端点的隐藏散点)交互,忽略误差棒线体、端点帽的交互
  • 悬浮提示仅展示对应点的y轴数值,保留一位小数精度

完整实现代码

import pandas as pd
import matplotlib.pyplot as plt
import mplcursors

df = pd.DataFrame(
    {'Universe': ['Darvel', 'MC', 'MC', 'Darvel', 'MC', 'Other', 'Darvel'],
     'Value': [10, 11, 13, 12, 9, 7, 10],
     'Upper': [12.5, 11.3, 15.4, 12.2, 13.1, 8.8, 11.5],
     'Lower': [4.5, 9.6, 11.8, 6, 6.5, 5, 8]})
df['UpperError'] = df['Upper'] - df['Value']
df['LowerError'] = df['Value'] - df['Lower']

colors = ['r', 'g', 'b']
# 存储所有散点实例,用于限定交互范围
scatter_artists = []

fig, ax = plt.subplots()
for i, universe in enumerate(df['Universe'].unique()):
    to_plot = df[df['Universe'] == universe]
    # 中间数值散点
    sc_val = ax.scatter(to_plot.index, to_plot['Value'], s=16, c=colors[i])
    scatter_artists.append(sc_val)
    
    error = to_plot[['LowerError', 'UpperError']].transpose().to_numpy()
    ax.errorbar(to_plot.index, to_plot['Value'], yerr=error, fmt='o',
                markersize=0, capsize=6, color=colors[i])
    
    # 误差棒上端散点
    sc_upper = ax.scatter(to_plot.index, to_plot['Upper'], c='w', zorder=-1)
    scatter_artists.append(sc_upper)
    # 误差棒下端散点
    sc_lower = ax.scatter(to_plot.index, to_plot['Lower'], c='w', zorder=-1)
    scatter_artists.append(sc_lower)

# 仅为散点对象绑定光标交互
cursor = mplcursors.cursor(artists=scatter_artists, hover=True)

# 自定义悬浮提示内容,仅展示y轴数值
@cursor.connect("add")
def on_add(sel):
    sel.annotation.set_text(f"{sel.target[1]:.1f}")
    # 可选:设置提示框背景样式,提升可读性
    sel.annotation.get_bbox_patch().set(fc="white", alpha=0.9, edgecolor="#cccccc")

plt.show()

关键修改说明

  • 新增scatter_artists列表收集所有散点对象,初始化光标时通过artists参数限定交互范围,误差棒的线体、帽端不会触发交互
  • 通过cursor.connect绑定触发事件,直接读取选中点的y轴坐标格式化输出,精度保留1位小数,符合需求的展示效果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 09:42:00