我有这个静态数据集的数据范围从2015
到2016
,我想把所有的东西都映射出来,而不是手动添加自己的栏。
final_water_supply
数据图像表示
var ctx = document.getElementById('mc').getContext('2d');
chartRef1 = new Chart(ctx, {
type: 'bar',
data: {
labels: sortedData,
datasets: [{
label: '2015',
stack: 'Stack 1',
data: final_water_supply[0],
backgroundColor: '#D0D1E6',
borderColor: '#D0D1E6',
},
{
label: '2016',
stack: 'Stack 2',
data: final_water_supply[1],
backgroundColor: '#74A9CF',
borderColor: '#74A9CF',
},
{
label: '2017',
stack: 'Stack 3',
data: final_water_supply[2],
backgroundColor: '#0570B0',
borderColor: '#0570B0',
},
{
label: '2018',
stack: 'Stack 4',
data: final_water_supply[3],
backgroundColor: '#023858',
borderColor: '#023858',
}
]
},
我就是这么做的
创建了一个空对象结构,它接受数据集
let color = '#d6d6d6'
let data = {
labels:sortedData,
datasets:[]
}
创建了一个forEach
函数,该函数遍历年份并将数据推入数据集
years.forEach(function(a,i) {
switch(i) {
case 0:
color='#D0D1E6'
break;
case 1:
color='#74A9CF'
break;
case 2:
color='#0570B0'
break;
case 3:
color='#023858'
break;
default:
color='#d6d6d6'
}
data.datasets.push({
label: a,
stack: 'Stack '+i,
data: final_water_supply[i],
backgroundColor: color,
borderColor: color,
})
})