次のデータポイントがあるとします。
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]}
];
各データセットの値は、さまざまなスタックバーに分散されます。したがって、必要なデータセットの数は、スタックバーに含めることができる値の最大数に対応します。
したがって、あなたの例では、次の3つのデータセットが必要です。
[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>
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加