Label is showing in bar chart - Javascript Chart.js

Javascript examples for Chart.js:Bar Chart

Description

Label is showing in bar chart

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <title>chart.js 2.0 bar</title> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.3/Chart.min.js"></script> 
      <script type="text/javascript">
    window.onload=function(){//  ww w. java  2  s  . c  o  m
var canvas = document.getElementById('myChart');
var data = {
  labels: ["January", "February", "March", "April", "May", "June"],
  datasets: [{
    label: "My First dataset",
    backgroundColor: "rgba(255,99,132,0.2)",
    borderColor: "rgba(255,99,132,1)",
    borderWidth: 2,
    hoverBackgroundColor: "rgba(255,99,132,0.4)",
    hoverBorderColor: "rgba(255,99,132,1)",
    data: [500, 2000, 800, 600, 950, 890],
  }]
};
function getOptions(displayLegend = false) {
  return {
    events: false,
    showTooltips: false,
    legend: {
      display: displayLegend
    },
    scales: {
      yAxes: [{
        display: true,
        stacked: true,
        ticks: {
           stepSize: 200,
          min: 0, // minimum value
          max: 2200 // maximum value, you can either hard code if you know your datainput, else computer the value through some logic i.e taking the max value from the dataset and adding some extra value to it.
        }
      }]
    },
    animation: {
      duration: 0,
      onComplete: function() {
        var ctx = this.chart.ctx;
        ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontFamily, 'normal', Chart.defaults.global.defaultFontFamily);
        ctx.textAlign = 'center';
        ctx.textBaseLine = 'bottom';
        ctx.fillStyle = '#0b7707';
        this.data.datasets.forEach(function(dataset) {
          console.log(dataset);
          for (var i = 0; i < dataset.data.length; i++) {
            for (var key in dataset._meta) {
              var model = dataset._meta[key].data[i]._model;
              ctx.fillText(dataset.data[i], model.x, model.y - 10);
            }
          }
        });
      }
    }
  };
}
var myBarChart = Chart.Bar(canvas, {
  data: data,
  options: getOptions()
});
    }

      </script> 
   </head> 
   <body> 
      <canvas id="myChart" width="400" height="200"></canvas>  
   </body>
</html>

Related Tutorials