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

C3.js堆叠柱状图未按月份分组问题排查求助

问题分析与修复方案

你的代码存在两个核心问题,导致无法实现「每个产品下按月份堆叠展示销售额」的效果:

1. 对C3.js的groups配置理解错误

groups参数的作用是将多个数值系列(即keys.value里的字段)分组堆叠,但你传入的["month"]并不是数值字段,month是分类维度,因此这个配置完全无效。

2. 数据结构与配置不匹配

当前数据是「长格式」(每条记录对应一个产品-月份的销售额),但你配置的x: "product"会让C3把同一个产品的多条记录合并成一个x轴条目,最终只会显示每个产品的总销售额,无法拆分月份维度。


修复后的代码

需要调整数据处理逻辑和图表配置,让C3正确识别产品作为x轴分类、月份作为堆叠系列:

步骤1:转换数据格式(长格式转宽格式)

先把原数据转换成宽格式,让每个产品条目包含对应各月份的销售额字段:

// 手动转换示例(固定月份场景)
const formattedData = [
  {product: "Pulp", january: 320, february: 160},
  {product: "Beef", january: 210, february: 90}
];

// 动态转换代码(适用于未知月份/更多数据的场景)
/*
const formattedData = {};
data.forEach(item => {
  if (!formattedData[item.product]) {
    formattedData[item.product] = {product: item.product};
  }
  formattedData[item.product][item.month] = item.sale_amount;
});
const finalData = Object.values(formattedData);
*/

步骤2:调整图表配置

配置keys.value为月份字段,用groups将这些月份字段设为堆叠组,同时x轴绑定product:

var chart = c3.generate({
  data: {
    json: formattedData, // 使用转换后的宽格式数据
    keys: {
      x: "product",
      value: ["january", "february"] // 将月份作为独立数值系列
    },
    type: "bar",
    groups: [["january", "february"]] // 指定月份系列为堆叠组
  },
  axis: {
    x: {
      type: "category",
      label: {
        text: '产品',
        position: 'outer-center'
      }
    },
    y: {
      label: {
        text: '销售额',
        position: 'outer-middle'
      }
    }
  },
  legend: {
    show: true,
    position: 'bottom'
  }
});

核心逻辑说明

  • 宽格式数据让每个产品条目包含所有月份的销售额,C3能识别不同月份为独立数据系列
  • groups: [["january", "february"]]告诉C3将这两个月份系列堆叠展示,而非并列
  • x轴绑定product,确保每个x轴条目对应一个产品,其下堆叠不同月份的销售额

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 03:33:20