我有以下不同月份的数据
Jan:[1,5,3]
2月:[10,5]
3月:[4,8]
4月:[7]
五月:[3,1,5,0,7]
我想将条形图生成为波纹管
现在,我有以下代码,我想知道如何生成如上图所示的条形图。
new Chart(document.getElementById("bar-chart"), {
type: 'bar',
data: {
labels: ['Jan','Feb','Mar','Apr','May'],
datasets: [{
data: [1,5,3],
label: 'Jan',
backgroundColor: "#3e95cd",
}
, {
data: [10,5],
label: 'Feb',
backgroundColor: "#8e5ea2",
}, {
data: [4,8],
label: 'Mar',
backgroundColor: "#4287f5",
}
, {
data: [7],
label: 'Apr',
backgroundColor: "#23ebbc",
}
, {
data: [3,1,5,0,7],
label: 'May',
backgroundColor: "#e63057",
}
]
},
options: {
title: {
display: true,
text: 'This is title'
},
backgroundColor:'#cfcfcf',
scales: {
xAxes: [{ stacked: true }],
yAxes: [{ stacked: true }]
}
}
});
谢谢
答案 0 :(得分:1)
第一个数据集是[10,10,8,7,3]
,它是红色,第二个数据集是[5,5,8,0,1]
,第三个数据集[3,0,0,0,5]
,第四个数据集[0,0,0,0,7]
当然,您必须使用自己的技能来转换Web服务发送的数据。但这是您想要的最终结果。
答案 1 :(得分:0)
我只使用过ChartJS一次,但是根据您想要的判断,我假设您创建一个条形图并分别添加每个数据集。例如,数据集:[{{data:yourRedData}]然后将其附加到图表中。
接缝看起来好像确实有您想要的示例,https://www.chartjs.org/samples/latest/charts/bar/stacked.html
我检查了示例的源代码,以更好地了解它们如何获得结果,这就是我的发现。
var barChartData = {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
label: 'Dataset 1',
backgroundColor: window.chartColors.red,
data: [
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor()
]
}, {
label: 'Dataset 2',
backgroundColor: window.chartColors.blue,
data: [
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor()
]
}, {
label: 'Dataset 3',
backgroundColor: window.chartColors.green,
data: [
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor()
]
}]
};
window.onload = function() {
var ctx = document.getElementById('canvas').getContext('2d');
window.myBar = new Chart(ctx, {
type: 'bar',
data: barChartData,
options: {
title: {
display: true,
text: 'Chart.js Bar Chart - Stacked'
},
tooltips: {
mode: 'index',
intersect: false
},
responsive: true,
scales: {
xAxes: [{
stacked: true,
}],
yAxes: [{
stacked: true
}]
}
}
});
};