Chartjs-How can I add a label above just the last bar in a Chart.JS bar chart?

1👍

First, you were right thinking about using the afterDraw event with a plugin and I understand it can be quite a mess to find what we really want in all the data and options.

Yet, follows a plugin that will help you do what you are looking for :

var myPlugin = {
    afterDraw: function(chartInstance) {
        // We get the canvas context
        var ctx = chartInstance.chart.ctx;

        // And set all the properties we need
        ctx.font = Chart.helpers.fontString(14, 'bold', Chart.defaults.global.defaultFontFamily);
        ctx.textAlign = 'center';
        ctx.textBaseline = 'bottom';
        ctx.fillStyle = '#666';

        // We get the number of datasets we have in your chart
        var numOfDatasets = chartInstance.config.data.datasets.length;

        // For every dataset in our chart ...
        chartInstance.data.datasets.forEach(function(dataset) {

            // If it is not the last dataset, we return now (no action at all)
            if (dataset._meta[0].controller.index != numOfDatasets - 1) return;

            // For every data in the dataset ...
            for (var i = 0; i < dataset.data.length; i++) {

                // We get the previous dataset (to compare later)
                var previousDataset = chartInstance.config.data.datasets[dataset._meta[0].controller.index - 1];
                // And get the model of the current value
                var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model;

                // We calculate the percentage difference with the previous
                var value = ((dataset.data[i] - previousDataset.data[i]) / previousDataset.data[i]) * 100;

                // And write it with a "%" symbol
                // The ternary adds a "+" symbol if it is a positive value
                ctx.fillText((value > 0 ? "+" : "") + value.toFixed(1) + "%", model.x, model.y);
            }
        });
    }
};

Chart.pluginService.register(myPlugin);

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

enter image description here

Leave a comment