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

如何用Highcharts.js基于动态数据库数据创建堆叠柱状图

如何用Highcharts.js将PIVOT得到的数组数据转为堆叠柱状图

我通过数据库PIVOT操作得到如下数组数据:

const rawData = [
  { MonthsName: 'April', AUTOLIV: 0, Continental: 0, 'Herman miller': 0, REL: 0 },
  { MonthsName: 'July', AUTOLIV: 0, Continental: 4, 'Herman miller': 0, REL: 0 },
  { MonthsName: 'June', AUTOLIV: 1, Continental: 0, 'Herman miller': 0, REL: 0 },
  { MonthsName: 'May', AUTOLIV: 1, Continental: 0, 'Herman miller': 1, REL: 1 }
];

我希望将月份名称作为X轴,其余列的数值作为堆叠柱状图的堆叠值,请问如何使用Highcharts.js实现该需求?


实现方案

1. 转换数据格式

Highcharts的堆叠柱状图要求数据以series数组形式传入,每个series对应一个数据类别(如AUTOLIV、Continental),同时需要提取所有月份作为X轴分类。用以下代码完成转换:

// 提取所有月份作为X轴分类
const categories = rawData.map(item => item.MonthsName);

// 获取所有数据类别(排除MonthsName字段)
const categoryKeys = Object.keys(rawData[0]).filter(key => key !== 'MonthsName');

// 生成符合Highcharts要求的series数组
const series = categoryKeys.map(key => ({
  name: key,
  data: rawData.map(item => item[key]),
  stack: 'total' // 指定统一stack值,实现堆叠效果
}));

2. 初始化堆叠柱状图

先在页面创建图表容器,再引入Highcharts并初始化配置:

<!-- 图表容器 -->
<div id="stacked-chart" style="width: 100%; height: 400px;"></div>

<!-- 引入Highcharts -->
<script src="https://code.highcharts.com/highcharts.js"></script>
<script>
// 这里放入rawData、categories、series变量

Highcharts.chart('stacked-chart', {
  chart: {
    type: 'column' // 指定图表类型为柱状图
  },
  title: {
    text: '各月份类别数据堆叠柱状图'
  },
  xAxis: {
    categories: categories,
    title: { text: '月份' }
  },
  yAxis: {
    min: 0,
    title: { text: '数值' },
    // 显示堆叠总和标签
    stackLabels: {
      enabled: true,
      style: { fontWeight: 'bold', color: 'gray' }
    }
  },
  tooltip: {
    headerFormat: '<b>{point.x}</b><br/>',
    pointFormat: '{series.name}: {point.y}<br/>Total: {point.stackTotal}'
  },
  plotOptions: {
    column: {
      stacking: 'normal', // 开启堆叠模式,可选'percent'实现百分比堆叠
      dataLabels: {
        enabled: true,
        color: 'white'
      }
    }
  },
  series: series // 绑定转换后的series数据
});
</script>

关键说明

  • stack: 'total':所有series使用相同的stack标识,确保它们在同一组内堆叠。
  • stacking: 'normal':开启常规数值堆叠,若改为'percent'则会以百分比形式展示堆叠占比。
  • 数据转换逻辑自动适配原始数据中的类别,后续新增类别无需修改核心代码。

内容的提问来源于stack exchange,提问作者Edwin K Biju

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 01:46:15