C3.js 中的堆叠条形图不显示组

问题描述 投票:0回答:1

我正在尝试在 C3.js 中使用带有字段产品、月份、金额_销售的 JSON 制作堆叠条形图,例如:

[{"product": "Pulp", "month": "january", "sale_amount": 320},
{"product": "Pulp", "month": "february", "sale_amount": 160},
{"product": "Beef", "month": "january", "sale_amount": 210},
{"product": "Beef", "month": "february", "sale_amount": 90}]

然后我尝试生成一个堆叠条形图,显示每个产品每个月的销售额,代码如下:

var chart = c3.generate({
  data: {
    json: data,
    keys: {
      x: "product",
      value: ["sale_amount"]
    },
    type: "bar",
    groups: [["month"]]
  },
  axis: {
    x: {
      type: "category"
    }
  }
});

但是图表显示了 X 轴上的产品,但它不带月份组,我们可以看到:

https://codepen.io/NetWilson05/pen/bGmdMZR

我做错了什么?

javascript jquery c3.js stacked-bar-chart
1个回答
1
投票

JSON 格式错误,格式必须是:X, Col1, Col2,...

完整的例子是:

const data = [
  { "product": "Pulp", "month": "january", "sale_amount": 320 },
  { "product": "Pulp", "month": "february", "sale_amount": 160 },
  { "product": "Beef", "month": "january", "sale_amount": 210 },
  { "product": "Beef", "month": "february", "sale_amount": 90 }
];

const transformedData = data.reduce((acc, cur) => {
  const existingMonth = acc.find((item) => item.month === cur.month);
  
  if (existingMonth) {
    existingMonth[cur.product] = cur.sale_amount;
  } else {
    acc.push({ month: cur.month, [cur.product]: cur.sale_amount });
  }
  
  return acc;
}, []);

const chart = c3.generate({
  data: {
    json: transformedData,
    keys: {
      x: "month",
      value: ["Pulp", "Beef"]
    },
    type: "bar",
    groups: [["Pulp", "Beef"]]
  },
  axis: {
    x: {
      type: "category"
    }
  }
});

这是基于用户稍后删除的其他回复,我不知道为什么

© www.soinside.com 2019 - 2024. All rights reserved.