[Chartjs]-Create stacked bar chart with a single dataset per stack

2👍

The values of each dataset are distributed to the various stacked bars. Therefore, the required number of datasets corresponds to the maximum number of values that can be contained in a stacked bar.

Accordingly, for your example you need the following three datasets:

[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>

Leave a comment