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

Chart.js如何实现折线图任意位置悬停触发数据提示

Chart.js 柱线混合图表悬停交互异常修复

问题根因

  • 折线数据集绑定了独立的隐藏x轴xAxis2,该轴仅配置2个点位,且折线点半径pointRadius设为0,Chart.js默认悬停判定仅在命中数据元素(折线点、柱体)时触发,因此只有折线两个端点位置可以触发提示。
  • 两个x轴点位数量、索引不对齐:柱状图绑定的默认xAxis仅1个标签['Modes'],xAxis2配置了2个空标签,索引无法映射,因此悬停在折线第二个端点时,匹配不到对应柱状图数据集,仅显示折线自身数值。
  • 未配置悬停非交叉判定规则,鼠标未精准命中数据元素时不会触发提示。

修复步骤

  • 删除多余的隐藏x轴xAxis2配置,折线数据集复用柱状图的默认x轴,保证所有数据集x轴索引完全对齐,折线数据调整为和x轴标签数量匹配的单值。
  • 给hover和tooltip配置项添加intersect: false,配合mode: 'index',实现鼠标悬停在对应x索引列的任意位置(包含整条折线覆盖区域)都能触发提示。
  • 给折线配置pointHitRadius: 20,即使隐藏了折线点,也能扩大折线的悬停判定范围,降低命中难度。
  • 简化tooltip标题回调逻辑,保证悬停时正常显示分类标题。

修复后完整代码

ngOnInit(): void {   
  const myChart = new Chart('myChart', {
    type: 'bar',
    data: {
      labels: ['Modes'],
      datasets: [
        {
          label: 'A',
          data: [this.data.a],
          borderColor: 'rgba(255,105,180,1)',
          backgroundColor: 'rgba(255,105,180,0.2)',
          barPercentage: 0.4,
          borderWidth: 2,
          order: 1
        },
        {
          label: 'B',
          data: [this.data.b],
          borderColor: 'rgba(75, 192, 192, 1)',
          backgroundColor: 'rgba(75, 192, 192, 0.2)',
          barPercentage: 0.4,
          borderWidth: 2,
          order: 2
        },
        {
          label: 'Total Recordings',
          data: [this.data.totalrecordings],
          type: 'line',
          borderColor: 'rgba(2,117,216,1)',
          backgroundColor: 'rgba(2,117,216,0.2)',
          pointRadius: 0,
          pointHoverRadius: 0,
          pointHitRadius: 20,
          order: 0
        }
      ]
    },
    options: {
      responsive: true,
      hover: {
        mode: 'index',
        intersect: false
      },
      plugins: {
        legend: {
          position: 'top',
        },
        tooltip: {
          mode: 'index',
          intersect: false,
          callbacks: {
            title: (ttItems) => ttItems[0].label
          },
        }
      },
      scales: {
        xAxis: {}
      }
    },
  })
}

修复后鼠标悬停在折线任意位置、或是柱状图对应列的任意区域,都会同时展示A、B柱体数值和Total Recordings折线数值,不会出现仅端点触发、提示数据不全的问题。

异常效果参考截图

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 09:54:23