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

ApexCharts甜甜圈图表:实现悬浮时中心标签显示带千位分隔符的数值

ApexCharts甜甜圈图表:实现悬浮时中心标签显示带千位分隔符的数值

看起来你已经搞定了甜甜圈中心总数值的千位分隔符,但悬浮切换到单系列数值时就“掉链子”了,这个问题我帮你解决~

首先得说清楚为啥之前的设置没生效:你加在plotOptions.donut.labels.value.formatter里的格式化函数,只对非悬浮状态下的单系列数值生效。而当你hover到甜甜圈区块时,ApexCharts会自动替换中心文本,这个过程默认不会调用那个formatter,所以我们得换个思路——用自定义标签函数来接管所有状态下的中心文本显示。

直接上解决方案,修改你的plotOptions.pie.donut.labels配置,把原来的total和value换成custom函数,同时关闭默认的名称显示:

const options = {
  series: [12039, 1899],
  chart: {
    type: "donut"
  },
  title: {
    text: "Customers Within Standards",
    align: "center",
    style: {
      fontSize: "14px"
    }
  },
  labels: ["Within Standards", "Not Within Standards"],
  dataLabels: {
    enabled: false
  },
  plotOptions: {
    pie: {
      customScale: 0.8,
      expandOnClick: false,
      dataLabels: {
        enabled: false
      },
      donut: {
        size: "60%",
        labels: {
          show: true,
          name: {
            show: false // 隐藏系列名称,只显示数值
          },
          // 用custom函数接管所有状态的中心文本
          custom: function(opts) {
            let value;
            // 判断是否hover在某个系列上
            if (opts.seriesIndex !== undefined) {
              // 悬浮状态:取当前系列的数值
              value = opts.w.config.series[opts.seriesIndex];
            } else {
              // 默认状态:计算总数值
              value = opts.w.config.series.reduce((a, b) => a + b, 0);
            }
            // 格式化数值为带千位分隔符的字符串
            return value.toLocaleString();
          }
        }
      }
    }
  },
  legend: {
    position: "bottom",
    offsetY: -20
  },
  tooltip: {
    enabled: false
  }
};

代码逻辑说明:

  • custom函数接收的opts参数里,seriesIndex是关键:当hover在某个区块时,它会被赋值为对应的系列索引;默认状态下是undefined。
  • 针对两种状态分别获取对应数值,然后统一用toLocaleString()格式化,完美适配千位分隔符(还能自动适配不同地区的格式哦)。
  • 如果你需要保留系列名称,也可以调整custom函数的返回值,比如return ${opts.w.config.labels[opts.seriesIndex]}: ${value.toLocaleString()};

把这个配置替换到你的代码里试试,不管是默认显示的总数值,还是hover时的单系列数值,都会带上千位分隔符啦~

备注:内容来源于stack exchange,提问作者VeggieBear

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 17:38:00