说我有以下数据点:
let points = [
{key: "foo", value: 1},
{key: "foo", value: 2},
{key: "foo", value: 1},
{key: "bar", value: 2},
{key: "bar", value: 1}
];
我想创建一个类似于以下内容的图表:
5 +-------------------------------+
| |
4 | +-----+ |
| | | |
3 | +-----+ +-----+ |
| | | | | |
2 | | | +-----+ |
| | | | | |
1 | +-----+ | | |
| | | | | |
0 +------+-----+------+-----+-----+
foo bar
实际的数据集有许多不同的堆栈,在此示例中,我对其进行了简化。我已经可以通过以下方法实现效果,但是每个点都被视为自己的数据集,我觉得应该有一个更干净,更有效的解决方案:
let datasets = [
{label: "foo", stack: "foo", data: [1]},
{label: "foo", stack: "foo", data: [2]},
{label: "foo", stack: "foo", data: [1]},
{label: "bar", stack: "bar", data: [2]},
{label: "bar", stack: "bar", data: [1]}
];
每个数据集的值分配到各个堆叠的条形。因此,所需的数据集数量对应于可容纳在堆叠条形图中的最大值数量。
因此,对于您的示例,您需要以下三个数据集:
[1, 2]
[2, 1]
[1, 0]
<html>
<head>
<title>Stacked Bar Chart</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<style>
canvas {
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
}
</style>
</head>
<body>
<div style="width: 75%">
<canvas id="canvas"></canvas>
</div>
<script>
var data = {
labels: ['foo', 'bar'],
datasets: [{
backgroundColor: 'red',
data: [1, 2]
}, {
backgroundColor: 'green',
data: [2, 1]
}, {
backgroundColor: 'blue',
data: [1, 0]
}]
};
window.onload = function() {
var ctx = document.getElementById('canvas').getContext('2d');
window.myBar = new Chart(ctx, {
type: 'bar',
data: data,
options: {
title: {
display: true,
text: 'Stacked Bar Chart'
},
tooltips: {
mode: 'index',
intersect: false
},
legend: {
display: false
},
responsive: true,
scales: {
xAxes: [{
stacked: true,
}],
yAxes: [{
stacked: true
}]
}
}
});
};
</script>
</body>
</html>