[Chartjs]-How can I append a calculated value to the end of a bar in Chart.JS?

2๐Ÿ‘

โœ…

As you did with model.base when you are adding the data, do the following :

Chart.pluginService.register({
    afterDraw: function(chartInstance) {
        var ctx = chartInstance.chart.ctx;
        ctx.font = Chart.helpers.fontString(14, 'bold', Chart.defaults.global.defaultFontFamily);

        // `start` makes a better rendering IMO
        ctx.textAlign = 'start';
        ctx.textBaseline = 'bottom';
        ctx.fillStyle = '#666';

        chartInstance.data.datasets.forEach(function(dataset) {
            for (var i = 0; i < dataset.data.length; i++) {
                var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model;
                ctx.fillText(dataset.data[i], model.base + 5, model.y + 6);

                if (dataset._meta[0].controller.index == 1) {
                    // Orange bar (2nd dataset) values here

                    // We get the other dataset
                    var otherDataset = chartInstance.data.datasets[(dataset._meta[0].controller.index == 1) ? 0 : 1];

                    // Then calculate the percentage difference
                    var value = Math.round((Math.abs(dataset.data[i] - otherDataset.data[i]) / otherDataset.data[i]) * 100);

                    // And finally we display it
                    ctx.fillText(value + "%", model.x + 5, model.y + 6);
                }
            }
        });
    }
});

You can see the plugin working in this jsFiddle, and here is how it looks like :

enter image description here

Leave a comment