Add a label above the last bar in a Chart.JS bar chart - Javascript Chart.js

Javascript examples for Chart.js:Bar Chart

Description

Add a label above the last bar in a Chart.JS bar chart

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.2/Chart.min.js"></script> 
      <script type="text/javascript">
    window.onload=function(){/*from  w  w w.j a  v  a 2s . co m*/
Chart.pluginService.register({
    afterDraw: function(chartInstance) {
        var ctx = chartInstance.chart.ctx;
        ctx.font = Chart.helpers.fontString(14, 'bold', Chart.defaults.global.defaultFontFamily);
        ctx.textAlign = 'center';
        ctx.textBaseline = 'bottom';
        ctx.fillStyle = '#666';
      var numOfDatasets = chartInstance.config.data.datasets.length;
        chartInstance.data.datasets.forEach(function(dataset) {
            if (dataset._meta[0].controller.index != numOfDatasets - 1) return;
            for (var i = 0; i < dataset.data.length; i++) {
               var previousDataset = chartInstance.config.data.datasets[dataset._meta[0].controller.index - 1];
                var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model;
                var value = ((dataset.data[i] - previousDataset.data[i]) / previousDataset.data[i]) * 100;
                ctx.fillText((value > 0 ? "+" : "") +value.toFixed(1) + "%", model.x, model.y);
            }
        });
    }
});
var ctxForecastChart = document.getElementById("forecastLineChart");
var forecastChartData = {
    labels: [
        "Total Sales"
    ],
    datasets: [{
        label: "8/28/2016 - 9/3/2016",
        backgroundColor: "rgba(255,0,0,0.75)",
        hoverBackgroundColor: "rgba(255,0,0,1)",
        data: [240]
    }, {
        label: "9/25/2016 - 10/2/2016",
        backgroundColor: "rgba(255,153,0,0.75)",
        hoverBackgroundColor: "rgba(255,153,0,1)",
        data: [272]
    }, {
        label: "9/18/2016 - 9/24/2016",
        backgroundColor: "rgba(255,255,0,0.75)",
        hoverBackgroundColor: "rgba(255,255,0,1)",
        data: [250]
    }, {
        label: "9/4/2016 - 9/10/2016",
        backgroundColor: "rgba(0,255,0,0.75)",
        hoverBackgroundColor: "rgba(0,255,0,1)",
        data: [232]
    }, {
        label: "9/11/2016 - 9/17/2016",
        backgroundColor: "rgba(0,0,255,0.75)",
        hoverBackgroundColor: "rgba(0,0,255,1)",
        data: [244]
    }]
};
var forecastOptions = {
    tooltips: {
        enabled: true
    }
};
var forecastBarChart = new Chart(ctxForecastChart, {
    type: 'bar',
    data: forecastChartData,
    options: forecastOptions
});
    }

      </script> 
   </head> 
   <body> 
      <canvas id="forecastLineChart"></canvas>  
   </body>
</html>

Related Tutorials