Chart.js to vertically insert the dataset values inside the bar graph - Javascript Chart.js

Javascript examples for Chart.js:Bar Chart

Description

Chart.js to vertically insert the dataset values inside the bar graph

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://rawgit.com/nnnick/Chart.js/v1.0.2/Chart.min.js"></script> 
      <script type="text/javascript">
    window.onload=function(){/*from   w  w w  . j a v a2s  .  c o m*/
function verticalLabel(ctx, data, dataToSplit, topOffset, spaceBetween, commaGap) {
  var i = 0, prev = 0;
  for (x of dataToSplit.toString().split("").reverse()) {
    if (x.indexOf(",") > -1) {
      ctx.fillText(x, data.x + commaGap, prev - topOffset);
    } else {
      ctx.fillText(x, data.x, data.y - spaceBetween * i - topOffset);
      i++;
    }
    var prev = data.y - spaceBetween * i;
  }
}
var chartData = {
  labels: ["January", "February", "March", "April", "May", "June"],
  datasets: [{
    fillColor: "#79D1CF",
    strokeColor: "#79D1CF",
    data: [6000, 80000, 8100, 5600, 5500, 4000]
  }]
};
var ctx = document.getElementById("myChart1").getContext("2d");
var myLine = new Chart(ctx).Line(chartData, {
  showTooltips: false,
  onAnimationComplete: function() {
    var ctx = this.chart.ctx;
    ctx.font = this.scale.font;
    ctx.fillStyle = this.scale.textColor
    ctx.textAlign = "center";
    ctx.textBaseline = "bottom";
    this.datasets.forEach(function(dataset) {
      dataset.points.forEach(function(points) {
        verticalLabel(ctx, points, addCommas(points.value), 10, 10, 4);
      });
    })
  }
});
function addCommas(nStr) {
  nStr += '';
  x = nStr.split('.');
  x1 = x[0];
  x2 = x.length > 1 ? '.' + x[1] : '';
  var rgx = /(\d+)(\d{3})/;
  while (rgx.test(x1)) {
    x1 = x1.replace(rgx, '$1' + ',' + '$2');
  }
  return x1 + x2;
}
var ctx = document.getElementById("myChart2").getContext("2d");
var myBar = new Chart(ctx).Bar(chartData, {
  showTooltips: false,
  onAnimationComplete: function() {
    var ctx = this.chart.ctx;
    ctx.font = this.scale.font;
    ctx.fillStyle = this.scale.textColor
    ctx.textAlign = "center";
    ctx.textBaseline = "bottom";
    this.datasets.forEach(function(dataset) {
      dataset.bars.forEach(function(bar) {
        verticalLabel(ctx, bar, addCommas(bar.value), 10, 10, 4);
      });
    })
  }
});
    }

      </script> 
   </head> 
   <body> 
      <canvas id="myChart1" height="300" width="500"></canvas> 
      <canvas id="myChart2" height="300" width="500"></canvas>  
   </body>
</html>

Related Tutorials