Display data values on bar chart using chart.js - Javascript Chart.js

Javascript examples for Chart.js:Bar Chart

Description

Display data values on bar chart using chart.js

Demo Code

ResultView the demo in separate window

<html lang="en">
   <head> 
      <title>#doc: responsive chart</title> 
      <style>

body {/*  w  w  w. ja  v a2 s  .c  o m*/
   background: #1D1F20;
   padding: 16px;
}
canvas {
   border: 1px dotted red;
}
.chart-container {
   position: relative;
   margin: auto;
   height: 80vh;
   width: 80vw;
}


      </style> 
   </head> 
   <body translate="no"> 
      <div class="chart-container"> 
         <canvas id="chart"></canvas> 
      </div> 
      <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script> 
      <script>
      var data = {
  labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul"],
  datasets: [{
    label: "Dataset #1",
    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: [65, 59, 20, 81, 56, 55, 40],
  }]
};
var options = {
  maintainAspectRatio: false,
  scales: {
    yAxes: [{
      stacked: true,
      gridLines: {
        display: true,
        color: "rgba(255,99,132,0.2)"
      }
    }],
    xAxes: [{
      gridLines: {
        display: false
      }
    }]
  }
};
        Chart.plugins.register({
            afterDatasetsDraw: function(chart, easing) {
                var ctx = chart.chart.ctx;
                chart.data.datasets.forEach(function (dataset, i) {
                    var meta = chart.getDatasetMeta(i);
                    if (!meta.hidden) {
                        meta.data.forEach(function(element, index) {
                            ctx.fillStyle = 'rgb(0, 0, 0)';
                            var fontSize = 16;
                            var fontStyle = 'normal';
                            var fontFamily = 'Helvetica Neue';
                            ctx.font = Chart.helpers.fontString(fontSize, fontStyle, fontFamily);
                            var dataString = dataset.data[index].toString();
                            ctx.textAlign = 'center';
                            ctx.textBaseline = 'middle';
                            var padding = 5;
                            var position = element.tooltipPosition();
                            ctx.fillText(dataString, position.x, position.y - (fontSize / 2) - padding);
                        });
                    }
                });
            }
        });
Chart.Bar('chart', {
  options: options,
  data: data
});
      //# sourceURL=pen.js
    
      </script>  
   </body>
</html>

Related Tutorials