Append a calculated value to the end of a bar in Chart.JS - Javascript Chart.js

Javascript examples for Chart.js:Bar Chart

Description

Append a calculated value to the end of a bar in Chart.JS

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(){/* w  w w  .jav a 2  s . c o m*/
var ctxForecastChart = document.getElementById("forecastLineChart");
    Chart.pluginService.register({
        afterDraw: function(chartInstance) {
            var ctx = chartInstance.chart.ctx;
            ctx.font = Chart.helpers.fontString(14, 'bold', Chart.defaults.global.defaultFontFamily);
            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) {
                        var otherDataset = chartInstance.data.datasets[(dataset._meta[0].controller.index == 1) ? 0 : 1];
                        var value = Math.round((Math.abs(dataset.data[i] - otherDataset.data[i]) / otherDataset.data[i]) * 100);
                        ctx.fillText(value + "%", model.x + 5, model.y + 6);
                    }
                }
            });
        }
    });
var forecastChartData = {
    labels: [
        "Total Qty", "Total Sales"
    ],
    datasets: [{
        label: "9/18/2016",
        backgroundColor: "rgba(34,139,34,0.75)",
        hoverBackgroundColor: "rgba(34,139,34,1)",
        data: [100, 1000.00]
    }, {
        label: "9/25/2016",
        backgroundColor: "rgba(255,153,51,0.75)",
        hoverBackgroundColor: "rgba(255,153,51,1)",
        data: [110, 1110.11]
    }]
};
var optionsForecast = {
    tooltips: {
        enabled: true
    }
};
var forecastBarChart = new Chart(ctxForecastChart, {
    type: 'horizontalBar',
    data: forecastChartData,
    options: optionsForecast
});
    }

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

Related Tutorials