[Chartjs]-ChartJS โ€“ Set different hover-text than x-axis description

14๐Ÿ‘

โœ…

You can achieve this using ticks callback function (for trimming the x-axis labels) and tooltips callback function (to dispaly the original text on tooltips)

var ctx = document.getElementById('c').getContext('2d');
var myChart = new Chart(ctx, {
   type: 'bar',
   data: {
      labels: ['January', 'February', 'March', 'April', 'May'],
      datasets: [{
         data: [1, 2, 3, 4, 5],
         backgroundColor: ['#30799f', '#ac51c3', '#4ba57b', '#e3297d', '#e35c32'],
         borderColor: ['#30799f', '#ac51c3', '#4ba57b', '#e3297d', '#e35c32'],
         borderWidth: 1
      }]
   },
   options: {
      responsive: false,
      scales: {
         xAxes: [{
            ticks: {
               callback: function(t) {
                  var maxLabelLength = 3;
                  if (t.length > maxLabelLength) return t.substr(0, maxLabelLength) + '...';
                  else return t;
               }
            }
         }],
         yAxes: [{
            ticks: {
               beginAtZero: true,
               stepSize: 1
            }
         }]
      },
      legend: {
         display: false
      },
      tooltips: {
         callbacks: {
            title: function(t, d) {
               return d.labels[t[0].index];
            }
         }
      }
   }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="c" width="350" height="200"></canvas>

Leave a comment