Chartjs-Chart.JS Not Formatting Y-Axis-1 Properly

1👍

This is because, you are returning same tooltip label for both the datasets.

You should rather use the following tooltips callback function :

callbacks: {
   label: function(t, d) {
      if (t.datasetIndex === 0) {
         var xLabel = d.datasets[t.datasetIndex].label;
         var yLabel = t.yLabel;
         return xLabel + ': ' + yLabel + '%';
      } else {
         var xLabel = d.datasets[t.datasetIndex].label;
         var yLabel = t.yLabel >= 1000 ? '$' + t.yLabel.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") : '$' + t.yLabel;
         return xLabel + ': ' + yLabel;
      }
   }
}

ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ

var labelsarr = ["Richard 14", "Richard 15", "Jason 14", "Jason 15", "Jack 14", "Jack 15"];
var values = [1, 2, 3, 4, 5, 6];
var values1 = [1, 2, 3, 4, 5, 6];

var ctx = document.getElementById('canvas1').getContext('2d');
var chart = new Chart(ctx, {
   type: 'bar',
   data: {
      labels: labelsarr,
      datasets: [{
         type: 'line',
         fill: false,
         label: 'Sale Total',
         backgroundColor: 'rgba(255,0,0,1)',
         borderColor: 'rgba(255,0,0,1)',
         data: values1,
         yAxisID: 'y-axis-1'
      }, {
         label: 'Sale Total',
         backgroundColor: 'rgba(0, 129, 214, 0.8)',
         data: values
      }]
   },
   options: {
      tooltips: {
         callbacks: {
            label: function(t, d) {
               if (t.datasetIndex === 0) {
                  var xLabel = d.datasets[t.datasetIndex].label;
                  var yLabel = t.yLabel;
                  return xLabel + ': ' + yLabel + '%';
               } else {
                  var xLabel = d.datasets[t.datasetIndex].label;
                  var yLabel = t.yLabel >= 1000 ? '$' + t.yLabel.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") : '$' + t.yLabel;
                  return xLabel + ': ' + yLabel;
               }
            }
         }
      },
      legend: {
         display: false,
         position: 'top',
      },
      scales: {
         yAxes: [{
            ticks: {
               beginAtZero: true,
               callback: function(value, index, values) {
                  if (parseInt(value) >= 1000) {
                     return '$' + value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
                  } else {
                     return '$' + value;
                  }
               }
            }
         }, {
            id: 'y-axis-1',
            position: 'right',
            ticks: {
               beginAtZero: true,
               callback: function(value, index, values) {
                  return value + '%';
               }
            }
         }]
      }
   }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="canvas1"></canvas>

Leave a comment