[Chartjs]-Chart.js โ€“ Draw charts with opposite bars โ€“ How to set both the y-axis ends to positive number?

2๐Ÿ‘

โœ…

You can use the stacking and custom ticks feature to produce the result you want.

Sample JS Fiddle

var ctx = document.getElementById('wrapper').getContext('2d');
var chart = new Chart(ctx, {
    // The type of chart we want to create
    type: 'bar',

    // The data for our dataset
    data: {
        labels: ["January", "February", "March", "April", "May", "June", "July"],
        datasets: [{
            label: "My First dataset",
            backgroundColor: 'rgb(255, 99, 132)',
            borderColor: 'rgb(255, 99, 132)',
            data: [0, 10, 5, 2, 20, 30, 45],
            stack: 'a'
        }, {
            label: "My Second dataset",
            backgroundColor: 'rgb(2, 99, 132)',
            borderColor: 'rgb(2, 99, 132)',
            data: [-10, -110, -15, -12, -120, -130, -145],
            stack: 'b'
        }]
    },

    // Configuration options go here
    options: {
        scales: {
            xAxes: [{
                stacked: true
            }],
            yAxes: [{
                stacked: true,
                ticks: {
                    callback: function (value, index, values) {
                        return value < 0 ? -value : value;
                    }
                }
            }]
        }
    }
});

Leave a comment