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

ApexCharts:仅在Y值重叠时显示共享提示框

实现仅Y轴值相同时显示共享提示框的方案
  • 核心思路:通过自定义tooltip.formatter函数,触发提示框时主动遍历所有系列,筛选出同一X轴位置下Y值与当前点一致的点,将这些点的信息合并到提示框中,同时保持shared: false的配置。

  • 修改后的完整tooltip配置代码:

tooltip: {
  enabled: true,
  shared: false,
  intersect: true,
  formatter: function() {
    const currentPoint = this;
    const { x, y } = currentPoint;
    const matchedPoints = [];
    
    // 遍历所有系列,筛选同X同Y的点
    this.series.chart.series.forEach(series => {
      const point = series.points.find(p => p.x === x);
      // 用极小值处理浮点数精度问题,避免因小数误差导致匹配失败
      if (point && Math.abs(point.y - y) < 0.001) {
        matchedPoints.push(point);
      }
    });
    
    // 构建提示框内容
    let tooltipContent = `<span style="color:${currentPoint.color}">●</span> ${currentPoint.series.name}: <b>${currentPoint.y}%</b><br/>`;
    // 如果存在多个匹配点,追加其他点的信息
    if (matchedPoints.length > 1) {
      matchedPoints.forEach(point => {
        if (point !== currentPoint) {
          tooltipContent += `<span style="color:${point.color}">●</span> ${point.series.name}: <b>${point.y}%</b><br/>`;
        }
      });
    }
    // 添加X轴信息
    tooltipContent += `<br/>X轴: <b>${x}</b>`;
    return tooltipContent;
  },
  marker: {
    show: true
  },
},
  • 关键细节说明:
    • 浮点数精度处理:直接用===比较Y值可能因浮点数存储误差导致匹配失败,所以用Math.abs(point.y - y) < 0.001做近似相等判断,精度阈值可根据实际需求调整。
    • 系列遍历逻辑:通过this.series.chart.series获取图表所有系列,再通过find方法定位每个系列中与当前点X值一致的数据点。
    • 格式兼容:保留了原配置中Y值加%、显示X轴信息的需求,同时用系列对应颜色的标记区分不同数据系列。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 11:56:34