Bar Chart on ChartJS

by Hifni Nazeer

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.0/Chart.min.js"></script>
<canvas id="myChart" width="400" height="100"></canvas>
<button id="btnGetChart">Get Chart</button>
<div>
  Stacked
</div>
<canvas id="myChart2" width="400" height="100"></canvas>
<button id="btnGetChart2">Get Chart</button>

JavaScript

$(document).ready(function() {
  $('#btnGetChart').click(function() {
    var ctx = document.getElementById("myChart").getContext('2d');
    var myChart = new Chart(ctx, {
      type: 'horizontalBar',
      data: {
        labels: ["Red", "Blue"],
        datasets: [{
          label: '# of Votes',
          data: [12000, 59897],
          backgroundColor: [
            'rgba(255, 99, 132, 0.2)',
            'rgba(54, 162, 235, 0.2)'
          ],
          borderColor: [
            'rgba(255,99,132,1)',
            'rgba(54, 162, 235, 1)'
          ],
          borderWidth: 1
        }]
      },
      options: {
        scales: {
          yAxes: [{
            ticks: {
              beginAtZero: true
            }
          }],
          xAxes: [{
            ticks: {
              callback: function(value, index, values) {
                //return value / 1000 + 'k';
                return value.toLocaleString();
              }
            }
          }]
        },
        //tooltip
        tooltips: {
          callbacks: {
            label: function(tooltipItem, data) {
              // get the data label and data value to display
              // convert the data value to local string so it uses a comma seperated number
              var dataLabel = data.labels[tooltipItem.index];
              var value = ': ' + data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index].toLocaleString();

              // make this isn't a multi-line label (e.g. [["label 1 - line 1, "line 2, ], [etc...]])
              if (Chart.helpers.isArray(dataLabel)) {
                // show value on first line of multiline label
                // need to clone because we are changing the value
                dataLabel = dataLabel.slice();
                dataLabel[0] += value;
              } else {
                dataLabel += value;
              }

              // return the text to display on the tooltip
              return dataLabel;

            }
          }
     ...