gpt4 book ai didi

javascript - Highchart聚合JSON数据

转载 作者:行者123 更新时间:2023-12-02 21:00:06 26 4
gpt4 key购买 nike

尝试在 React 中使用 highcharts,我的数据采用以下格式:

data: [{
country: 'USA',
color: '#00FF00',
population: 10
},
{
country: 'USA',
color: '#00FF00',
population: 2
},
{
country: 'Canada',
color: '#00FF00',
population: 13
}]

我想要实现的目标:柱形图,每个独特的国家/地区有一个条形图(在本示例中,美国和加拿大有两个条形图),每个条形图应显示人口总和。也就是说,美国为 12,加拿大为 13。此外,xAxis 名称应为 USACanada

highchart 是否提供开箱即用的分组依据/求和选项来解决我的问题?

当我搜索“highchart 数据聚合”时,第一个结果将我带到 documentation但这没有帮助。相关jsfiddle: https://jsfiddle.net/smj8qwun/1/

最佳答案

您必须将数据简化为您正在寻找的格式,如下所示:

let o = {
data: [{
country: "USA",
color: "#00FF00",
population: 10,
},
{
country: "USA",
color: "#00FF00",
population: 2,
},
{
country: "Canada",
color: "#00FF00",
population: 13,
},
]
}

let formattedData = o.data.reduce((p, c) => {
let found = p.find((o) => o.country === c.country);
if (found) {
found.y += c.population;
} else {
let {
population,
...rest
} = c;
p.push({ ...rest,
y: population
});
}
return p;
}, []);

Highcharts.chart('container', {
chart: {
type: 'column'
},

xAxis: {
categories: formattedData.map(o => o.country)
},
plotOptions: {
series: {
// general options for all series
dataGrouping: {
enabled: true,
}
},
},

series: [{
data: formattedData
}]
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>

<div id="container" style="height: 400px"></div>

关于javascript - Highchart聚合JSON数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61377075/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com