Chartjs-Chart.JS Format Labels For DataSets Differently

2👍

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 if (t.datasetIndex === 1) {
         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 = ["Red 12", "Red 13", "Yellow 12", "Yellow 13", "Blue 12", "Blue 13"];

var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
   type: 'bar',
   data: {
      labels: labelsarr,
      datasets: [{
         type: 'line',
         fill: false,
         label: 'Percent',
         backgroundColor: 'rgba(255,0,0,1)',
         borderColor: 'rgba(255,0,0,1)',
         data: [3, 4, 10, 5, 8, 7],
      }, {
         data: [12, 19, 3, 5, 2, 3],
         label: 'Total Revenue',
         backgroundColor: 'rgba(0, 129, 214, 0.8)',
      }]
   },
   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 if (t.datasetIndex === 1) {
                  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;
                  }
               }
            }
         }]
      }
   },
   plugins: [{
      beforeDraw: function(chart) {
         var labels = chart.data.labels;
         labels.forEach(function(e, i) {
            var bar = chart.data.datasets[1]._meta[0].data[i]._model;
            var dataPoint = e.split(/\s/)[1];
            if (dataPoint === '12')
               bar.backgroundColor = 'blue';
            else if (dataPoint === '13')
               bar.backgroundColor = 'orange';
         });
      }
   }]
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="myChart"></canvas>

some syntax issues have been fixed, look for those carefully.

Leave a comment