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

如何自定义Plotly的hover tooltip,解决曲线长名称悬停显示无法区分问题

Plotly长名称曲线悬停提示自定义方案

实现思路

不需要修改原始name字段,提前对每个曲线的名称做预处理提取可区分的短标识,结合Plotly的customdata和hovertemplate配置即可实现需求,同时避免默认超长名称展示的问题。

完整实现代码

var data = [
    {
        type: 'scatter',
        mode: 'lines+markers',
        name: 'Main.app.folder.section31.floor17.room8.box56.label6.nameA',
        x: [1,2,3,4,5],
        y: [2.02825,1.63728,6.83839,4.8485,4.73463],
        showlegend: false
    },
    {
        x: [1,2,3,4,5],
        y: [3.02825,2.63728,4.83839,3.8485,1.73463],
        name: 'Main.app.folder.section31.floor17.room8.box56.label6.different',
        showlegend: false
    },
    {
        type: 'scatter',
        mode: 'lines+markers',
        name: 'Main.app.folder.section31.floor17.room8.box56.label6.unknown',
        x: [1,2,3,4,5],
        y: [5.02825,4.63728,3.83839,2.8485,0.73463],
        showlegend: false
    },
]; 

// 批量处理所有曲线配置
data.forEach(trace => {
    // 可根据需求选择短名称生成规则
    // 规则1:取最后一个.之后的字段,直接得到nameA、different、unknown
    const shortLabel = trace.name.split('.').pop();
    // 规则2:保留末尾10位字符加前缀省略号,实现...bel6.nameA这类效果
    // const shortLabel = '...' + trace.name.slice(-10);
    
    // 将短标识存入customdata供hover模板调用
    trace.customdata = shortLabel;
    // 自定义hover模板,<extra></extra>用于隐藏默认追加的完整name
    trace.hovertemplate = '%{customdata}<br>坐标:(%{x}, %{y})<extra></extra>';
})

var layout = {
    title: "Set hover text with hovertemplate",
};

Plotly.newPlot('myDiv', data, layout);

关键说明

  • <extra></extra>标签是核心配置,空内容的<extra>会关闭Plotly默认在悬停提示末尾追加完整trace name的逻辑,避免出现冗余的超长名称
  • 短标识的生成规则可以灵活调整,完全匹配你的展示需求
  • 原始name字段不会被修改,不影响其他依赖完整名称的业务逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 23:15:04