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

ApexCharts堆叠柱状图:同时显示分段数据与列总和的实现问题

解决ApexCharts堆叠柱状图同时显示分段数据与列总和的问题

要实现堆叠柱状图同时展示各分段数据和每列总和,可通过以下配置完成:

1. 为每个系列单独配置dataLabels显示分段数据

在每个数据系列中添加dataLabels配置,开启分段数据的显示,并自定义格式与样式:

var options = {
  series: [{
    name: 'PRODUCT A',
    data: [44, 55, 41, 67, 22, 43],
    // 配置PRODUCT A的分段数据标签
    dataLabels: {
      enabled: true,
      formatter: function(val) {
        return val + "%";
      },
      style: {
        colors: ["#ffffff"], // 白色文字适配深色柱子
        fontSize: '12px'
      }
    }
  }, {
    name: 'PRODUCT B',
    data: [13, 23, 20, 8, 13, 27],
    // 配置PRODUCT B的分段数据标签
    dataLabels: {
      enabled: true,
      formatter: function(val) {
        return val + "%";
      },
      style: {
        colors: ["#333333"], // 深色文字适配浅色柱子
        fontSize: '12px'
      }
    }
  }],
  // 原有基础配置保持不变
  chart: {
    type: 'bar',
    height: 350,
    stacked: true,
    toolbar: {
      show: true
    },
    zoom: {
      enabled: true
    }
  },
  responsive: [{
    breakpoint: 480,
    options: {
      legend: {
        position: 'bottom',
        offsetX: -10,
        offsetY: 0
      }
    }
  }],
  plotOptions: {
    bar: {
      horizontal: false,
      borderRadius: 10
    },
  },
  xaxis: {
    type: 'datetime',
    categories: ['01/01/2011 GMT', '01/02/2011 GMT', '01/03/2011 GMT', '01/04/2011 GMT',
      '01/05/2011 GMT', '01/06/2011 GMT'
    ],
  },
  legend: {
    position: 'right',
    offsetY: 40
  },
  fill: {
    opacity: 1
  },
  // 2. 添加annotations配置显示每列总和
  annotations: {
    points: (function() {
      // 计算每列的总和
      const totals = options.series[0].data.map((val, idx) => val + options.series[1].data[idx]);
      // 生成每个总和的标注点
      return totals.map((total, idx) => ({
        x: options.xaxis.categories[idx],
        y: total,
        label: {
          text: total + "%",
          offsetY: -30, // 调整标签位置到柱子顶部上方
          style: {
            fontSize: '14px',
            fontWeight: 'bold',
            colors: ["#304758"]
          }
        }
      }));
    })()
  }
};

var chart = new ApexCharts(document.querySelector("#chart"), options);
chart.render();

配置说明

  • 每个系列的dataLabels:单独控制该分段的数据显示,通过style.colors设置文字颜色适配柱子背景,保证可读性。
  • annotations.points:通过自执行函数计算每列总和,在对应柱子顶部生成总和标签,offsetY调整标签与柱子顶部的距离,避免重叠。

HTML部分保持不变:

<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
<div id="chart"></div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 13:35:33