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

如何为带钻取的Highcharts饼图设置差异化提示框数值格式?

解决方案:动态切换Tooltip格式(百分比/公吨)

当然可以实现这个需求!Highcharts的Tooltip支持通过formatter函数来动态渲染内容,正好能满足你主饼图显示百分比、钻取后显示公吨(MT)的要求。

核心思路

我们不再使用固定的pointFormat,而是改用formatter函数,在函数内部判断当前图表的状态,然后分别输出对应的格式:

  • 主饼图(剩余百分比、实际百分比):显示X.XX%
  • 钻取后的产品数据:显示X.XX MT

修改后的完整代码

function visitorData(data){ 
  var products = data.products; 
  var remainingPercentage=data.remainingPercentage; 
  var actualPercentage=data.actualPercentage;

  Highcharts.chart('current', { 
    credits: { enabled: false }, 
    chart: { type: 'pie' }, 
    title: { text: 'Production report of current quarter' }, 
    subtitle: { }, 
    plotOptions: { 
      series: { 
        dataLabels: { enabled: true, } 
      } 
    }, 
    tooltip: { 
      headerFormat: '<span style="font-size:11px">{series.name}</span><br>',
      // 替换pointFormat为formatter函数,实现动态格式切换
      formatter: function() {
        // 判断当前是否为钻取后的产品系列(通过系列id匹配)
        if (this.series.id === 'ap') {
          // 钻取后显示公吨格式
          return `<span style="color:${this.point.color}">${this.point.name}</span>: <b>${this.point.y:.2f} MT</b><br/>`;
        } else {
          // 主饼图显示百分比格式
          return `<span style="color:${this.point.color}">${this.point.name}</span>: <b>${this.point.y:.2f}%</b> of total<br/>`;
        }
      }
    }, 
    series: [{ 
      name: 'Planned Production', 
      colorByPoint: true, 
      data: [{ 
        name: 'Remaining Production Qty. ', 
        y: data.remainingPercentage, 
      }, { 
        name: 'Actual Production Qty.', 
        y: data.actualPercentage, 
        drilldown: 'ap' 
      }] 
    }], 
    drilldown: { 
      series: [{ 
        name: 'production report', 
        id: 'po', 
        data: [ ] 
      }, { 
        name: 'Actual Production Qty.', 
        id: 'ap', 
        data: data.products 
      }] 
    } 
  }); 
}

关键代码解释

  1. tooltip.formatter函数:这是Highcharts提供的自定义Tooltip内容的核心方法,允许我们通过JS逻辑动态生成HTML内容,比固定的pointFormat更灵活。
  2. 系列判断逻辑:通过this.series.id === 'ap'精准识别钻取后的产品系列(对应你配置中id: 'ap'的钻取系列),确保格式切换的准确性。
  3. 格式适配:
    • 主饼图:保留你原本的百分比展示逻辑,显示{point.y:.2f}% of total
    • 钻取后:替换为公吨单位,显示{point.y:.2f} MT,匹配后端返回的产品数据格式

这样修改后,你的饼图就能完美实现主图显示百分比、钻取后显示公吨的需求啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:42:16