问题描述
我是Chartjs的新手,我希望在这里使用Chartjs来使用图表,我拥有json,所以我想显示为Sample Image is this ,所以请帮助我 和json数组是
[
{
"ChartGroupName": "Group-A","Apple": 45,"Banana": 37,"Kiwi_fruit": 60,"BlueBerry": 70,"Orange": 46,"Grape_Fruit": 33
},{
"ChartGroupName": "Group-B","Apple": 50,"Banana": 35,"Kiwi_fruit": 70,"BlueBerry": 65,"Orange": 40,"Grape_Fruit": 53
},{
"ChartGroupName": "Group-C","Apple": 55,"Banana": 39,"Kiwi_fruit": 80,"BlueBerry": 75,"Orange": 52,"Grape_Fruit": 73
}
]
解决方法
假设您的JSON
数据存在于名为data
的数组中,则可以如下生成labels
和datasets
:
const labels = Object.keys(data[0]).slice(1).map(l => l.replace('_',' '));
const datasets = data.map((o,i) => ({
label: o[0],data: Object.values(o).slice(1),backgroundColor: colors[i]
})
);
请查看以下可运行的代码段,说明其工作原理。
const data = [
{
"ChartGroupName": "Group-A","Apple": 45,"Banana": 37,"Kiwi_fruit": 60,"Blueberry": 70,"Orange": 46,"Grape_Fruit": 33
},{
"ChartGroupName": "Group-B","Apple": 50,"Banana": 35,"Kiwi_fruit": 70,"Blueberry": 65,"Orange": 40,"Grape_Fruit": 53
},{
"ChartGroupName": "Group-C","Apple": 55,"Banana": 39,"Kiwi_fruit": 80,"Blueberry": 75,"Orange": 52,"Grape_Fruit": 73
}
];
const colors = ['orange','yellow','lightblue']
const labels = Object.keys(data[0]).slice(1).map(l => l.replace('_',i) => ({
label: o['ChartGroupName'],backgroundColor: colors[i]
})
);
new Chart('myChart',{
type: 'bar',data: {
labels: labels,datasets: datasets
},options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}],}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart"></canvas>