高位图JSON中的堆积柱形图未绘制正确的值



我正在尝试绘制堆叠柱形图,但我得到的结果与JSON数据不匹配。

我有三个类别,但图表似乎没有出现在最后一个类别中。

为什么会发生这种情况?

我的代码:

let cat = [];
vals = json.map(val => {
return val.type;
});
console.log(vals);
vals.forEach(v=>{
if (cat.indexOf(v) === -1) cat.push(v);
});
console.log(cat);
const group_data = (array, key) => {
return array.reduce((a, c) => {
(a[c[key]] = a[c[key]] || []).push(c);
return a;
}, {});
}
const get_grouped = group_data(json, 'date');
console.log(get_grouped);
for (a in get_grouped) {
cat.forEach(t => {
if (!get_grouped[a].some(v => v.type == t)) {
get_grouped[a].push({
"date": get_grouped[a][0].date,
"metric": 0,
"type": t
});
}
})
}
console.log(get_grouped);
let series = Object.entries(get_grouped).map(([key, group]) => ({
['name']: key,
['data']: group.map(entry => entry['metric']),
['marker']: {
symbol: 'circle'
}
}));
console.log(series);
Highcharts.chart('container', {
chart: {
type: 'column'
},
title: {
text: 'Stacked column chart'
},
xAxis: {
categories: cat
},
legend: {
align: 'right',
x: -30,
verticalAlign: 'top',
y: 25,
floating: true,
backgroundColor:
Highcharts.defaultOptions.legend.backgroundColor || 'white',
borderColor: '#CCC',
borderWidth: 1,
shadow: false
},
tooltip: {
headerFormat: '<b>{point.x}</b><br/>',
pointFormat: '{series.name}: {point.y}<br/>Total: {point.stackTotal}'
},
plotOptions: {
column: {
stacking: 'normal'
}
},
series: series
}); 

这是我的小提琴:https://jsfiddle.net/noob0605/1y58t3fn/22/

据我所知,这是因为订单类别和数据不匹配。我该怎么解决?

您说得对,问题是类别的顺序与get_grouped对象中数据的顺序不匹配。您可以通过向for (a in get_grouped)循环添加排序(使每个数组中对象的顺序与cat中的顺序匹配(来解决此问题:

for (a in get_grouped) {
cat.forEach(t => {
if (!get_grouped[a].some(v => v.type == t)) {
get_grouped[a].push({
"date": get_grouped[a][0].date,
"metric": 0,
"type": t
});
}
});
get_grouped[a].sort((a, b) => cat.indexOf(a.type)-cat.indexOf(b.type));
}

使用splice将数据设置在特定类别索引处,而不是使用push。

for (a in get_grouped) {
cat.forEach((t, index) => {
if (!get_grouped[a].some(v => v.type == t)) {
const obj = {
"date": get_grouped[a][0].date,
"metric": 0,
"type": t
}
get_grouped[a].splice(index, 0, obj);
}
})
}

更新的Fiddlehttps://jsfiddle.net/technochamp/wj82bk60/1/

最新更新