You need to enable JavaScript to run this app. matplotlib复用单个标注对象致多数据集悬停标注仅单个生效的问题咨询
优惠活动
大模型
产品
解决方案
定价
更多

matplotlib复用单个标注对象致多数据集悬停标注仅单个生效的问题咨询

问题根因

标注仅在部分场景生效的问题完全来自hover函数的遍历逻辑缺陷,完全不需要为每个数据集单独创建独立标注对象,单个标注完全可以正常复用。
具体逻辑错误点:

  • 原代码在循环遍历所有散点集(plotter)时,只要遍历到任意一个未被鼠标命中的plotter,就会立刻执行隐藏标注的操作,完全不会等待所有plotter的命中判断完成。
  • 结合脚本的绘图顺序(先绘制蓝色正常散点集,再绘制红色异常散点集):
    • 鼠标悬停在蓝色点上时,第一个plotter命中触发标注显示,循环走到第二个plotter时因为未命中,直接把刚显示的标注隐藏;
    • 鼠标悬停在红色点上时,第一个plotter未命中,直接进入隐藏标注的分支,循环根本不会执行到第二个plotter的命中判断步骤;
      最终表现为标注仅能在个别场景下正常显示。
修复方案

仅需两处调整即可实现所有数据点的悬停触发:

  1. 重构hover函数的判断逻辑:先遍历所有plotter完成全部命中判断,记录下最后一个被命中的plotter对象,等全部遍历完成后再统一修改标注的文本、位置和可见状态,避免循环过程中过早修改标注状态被后续逻辑覆盖。
  2. 给每个散点集设置合理的picker参数(即鼠标离点的像素命中容差),避免默认容差太小导致难以触发悬停效果。
修复后完整可运行代码
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.ticker import AutoMinorLocator, MultipleLocator
from scipy.stats import linregress


# All data in pA*s
gc_data = {
'KAL1':{'Toluol':400754.594,'1-Octen':53695.014,'Decan':6443.483,'1-Nonannitril':48984.504},
'KAL2':{'Toluol':417583.343,'1-Octen':29755.3,'Decan':16264.896,'1-Nonannitril':16264.896},
'KAL3':{'Toluol':442378.88,'1-Octen':18501.12,'Decan':19226.245,'1-Nonannitril':16200.611},
'KAL4':{'Toluol':389679.589,'1-Octen':13381.415,'Decan':68549.002,'1-Nonannitril':11642.123},
'KAL5':{'Toluol':423982.487,'1-Octen':6263.286,'Decan':53580.809,'1-Nonannitril':4946.271},
'KAL6':{'Toluol':351754.329,'1-Octen':8153.602,'Decan':105408.823,'1-Nonannitril':7066.718}
}

# All data in mg
mass_data = {
'KAL1':{'1-Octen':149.3,'Decan':17.8,'1-Nonannitril':154.7},
'KAL2':{'1-Octen':80.6,'Decan':43.7,'1-Nonannitril':82.8},
'KAL3':{'1-Octen':50.4,'Decan':51.8,'1-Nonannitril':51.5},
'KAL4':{'1-Octen':40.9,'Decan':206.9,'1-Nonannitril':40.8},
'KAL5':{'1-Octen':18.0,'Decan':155.2,'1-Nonannitril':16.4},
'KAL6':{'1-Octen':23.4,'Decan':301.4,'1-Nonannitril':23.6},
}




def update_annot(line, annot, ind):

    if isinstance(line, matplotlib.collections.PathCollection):
        x,y = line.get_offsets().transpose()
    elif isinstance(line, matplotlib.lines.Line2D):
        x,y = line.get_data()
    else:
        quit('No getter of x,y Data for this type of plotter.')

    annot.xy = (x[ind["ind"][0]], y[ind["ind"][0]])
    text = "x = {:.4f}\ny= {:.4f}".format(x[ind["ind"][0]], y[ind["ind"][0]])
    annot.set_text(text)


def hover(event,fig,annot):
    # 鼠标不在绘图区域时直接隐藏标注
    if event.inaxes not in fig.axes:
        if annot.get_visible():
            annot.set_visible(False)
            fig.canvas.draw_idle()
        return
    plotters = fig.axes[0].collections
    hit_plotter = None
    hit_ind = None
    # 遍历所有plotter记录命中结果,不在循环中直接修改标注状态
    for plotter in plotters:
        cont, ind = plotter.contains(event)
        if cont:
            hit_plotter = plotter
            hit_ind = ind
    # 全部遍历完成后统一处理标注状态
    if hit_plotter is not None:
        update_annot(hit_plotter, annot, hit_ind)
        annot.set_visible(True)
    else:
        if annot.get_visible():
            annot.set_visible(False)
    fig.canvas.draw_idle()


def get_data(substance,standard):

    m = [mass_data[i][substance]/mass_data[i][standard] for i in mass_data] 
    A = [gc_data[i][substance]/gc_data[i][standard] for i in mass_data]

    return A,m



def plot(substance,standard,save=None):

    A,m = get_data(substance,standard)

    A_baddata = A.pop(1)
    m_baddata = m.pop(1)

    # Linear regression 
    a,b,rval,pval,stdev = linregress(A,m)

    # Plotting
    fig, ax = plt.subplots(figsize=(6,6))

    # Data inputs 增加picker参数设置悬停命中容差
    ax.scatter(A,m,marker='o', picker=5) # Measured data
    ax.scatter(A_baddata,m_baddata,marker='o',c='r', picker=5)

    xmin,xmax = ax.get_xlim()
    ymin,ymax = ax.get_ylim()
    ax.plot(np.array([-2*max(A),2*max(A)]),np.array([-2*max(A),2*max(A)])*a + b) # graph from regression parameters
    ax.set_ylim(ymin,ymax)
    ax.set_xlim(xmin,xmax)

    # General formatting
    ax.tick_params(axis='both',which='both',labelsize=12,direction='in')

    ax.xaxis.set_major_locator(MultipleLocator(1))
    ax.yaxis.set_major_locator(MultipleLocator(1))
    ax.xaxis.set_minor_locator(AutoMinorLocator())
    ax.yaxis.set_minor_locator(AutoMinorLocator())

    ax.set_ylabel(r'$m_{\mathrm{Substanz}}\quad/\quadm_{\mathrm{Standard}}$')
    ax.set_xlabel(r'$A_{\mathrm{Substanz}}\quad/\quadA_{\mathrm{Standard}}$')

    # Description Box
    textstr='{}{}\n'.format('Substanz: ',substance)
    textstr+='{}{}\n'.format('Standard: ',standard)
    textstr+='{}{:.5f}\n'.format('a = ',a)
    textstr+='{}{:.5f}\n'.format('b = ',b)
    textstr+='{}{:.5f}\n'.format(r'$R^{2}$ = ',rval)
    textstr+='{}{:.5f}\n'.format(r'$p$ = ',pval)
    textstr+='{}{:.5f}'.format(r'$\bar X = $',stdev)

    props = dict(boxstyle='round', fc='#96FBFF', ec='#3CF8FF', alpha=0.5)
    ax.text(0.05, 0.95, textstr, transform=ax.transAxes, fontsize=10,
            verticalalignment='top', bbox=props)


    if save:
        plt.savefig(substance+'.svg' ,bbox_inches='tight', transparent=True)
    else:
        # Hovering annotation
        ################################################################################################
        annot = ax.annotate("", xy=(0,0), xytext=(15,15),textcoords="offset points",
                            bbox=dict(boxstyle="round", fc="w", alpha=0.8),
                            arrowprops=dict(arrowstyle="->"))
        annot.set_visible(False)
        ################################################################################################

        fig.canvas.mpl_connect("motion_notify_event", lambda event: hover(event, fig, annot))
        plt.show()

plot('1-Nonannitril','Decan',0)

内容的提问来源于stack exchange,提问作者J.Doe

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.24 22:24:05