Chartjs-How can I calculate a value and place it inside the last bar in a Chart.JS bar chart?

0πŸ‘

βœ…

In your animation.onComplete callback, you can get the previous dataset with the following code :

// `dataset` here -----------------------------------------┐
// is the current dataset you are working on               |
// (since you loop through all of them in your callback)   V
var previousDataset = chartInstance.config.data.datasets[dataset._meta[Object.keys(dataset._meta)[0]].controller.index - 1];

Now that you can access the previous dataset, you can also get its value. Follows the full callback to make it more understandable :

var forecastOptions = {
    tooltips: {
        enabled: true
    },
    animation: {
        duration: 500,
        easing: "easeOutQuart",
        onComplete: function() {
            var ctx = this.chart.ctx;
            ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontFamily, 'normal', Chart.defaults.global.defaultFontFamily);
            ctx.textAlign = 'center';
            ctx.textBaseline = 'bottom';

            this.data.datasets.forEach(function(dataset) {
                for (var i = 0; i < dataset.data.length; i++) {

                    // We get the previous dataset here
                    var previousDataset = dataset._meta[Object.keys(dataset._meta)[0]].controller.chart.config.data.datasets[dataset._meta[Object.keys(dataset._meta)[0]].controller.index - 1];

                    var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model;
                    var scale_max = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._yScale.maxHeight;
                    ctx.fillStyle = '#444';
                    var y_pos = model.y - 5;
                    if ((scale_max - model.y) / scale_max >= 0.93)
                        y_pos = model.y + 20;

                    // If the previous dataset is not `undefined` (actually exists) ..
                    if(typeof previousDataset !== "undefined") {
                        // We write the data, with the difference with the previous one
                        ctx.fillText(dataset.data[i] + " (" + (dataset.data[i] - previousDataset.data[i]) + ")", model.x, y_pos);
                    }
                    else {
                        // We only write the data
                        ctx.fillText(dataset.data[i], model.x, y_pos);
                    }
                }
            });
        }
    }
};

You can see this callback working on this jsFiddle, and here is its result :

enter image description here

Note: Feel free to comment if you need any small changes such as a percentage difference instead.

Leave a comment