[Chartjs]-How can i add a calculated value on top of the bars in Chart.js?

2👍

You can register a new function using the pluginService for the afterDraw:

Chart.pluginService.register({
    afterDraw: function(chartInstance) {
        var ctx = chartInstance.chart.ctx;
        // render the value of the chart above the bar
        ctx.font = Chart.helpers.fontString(14, 'bold', Chart.defaults.global.defaultFontFamily);
        ctx.textAlign = 'center';
        ctx.textBaseline = 'bottom';

        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 + 10, model.y+5);
            }
        });
    }
});

If you need to calculate something you can replace dataset.data[i] in ctx.fillText with the calculated data you have.

Leave a comment