Chartjs-How to limit Chart.js label length on axes without affecting tooltips

3👍

Yes! That is possible.

As it seems from the screenshot given, you are using multi-line labels. If that is the case then, you can use the following x-axis ticks and tooltips callback functions to trim the labels on x-axis and show the complete text on tooltips respectively.

x-axis ticks callback (for trimming labels)

xAxes: [{
   ticks: {
      callback: function(label) {
         return label[0];
      }
   }
}]

tooltips title callback (for showing complete text)

tooltips: {
   callbacks: {
      title: function(t, d) {
         return d.labels[t[0].index];
      }
   }
}

working example :

var ctx = canvas.getContext('2d');
var chart = new Chart(ctx, {
   type: 'bar',
   data: {
      labels: [
         ['Corporate', 'Membership', '(Active)'],
         ['Group', 'Membership', '(Active)'],
         ['Muncipal', 'Level 2', '(300000-499999)', '(Active)'],
         ['Muncipal', 'Level 5', '(100000-399999)', '(Active)'],
         ['University', 'Membership', '(Active)']
      ],
      datasets: [{
         label: 'Members',
         data: [2, 4, 1, 3, 5],
         backgroundColor: 'rgba(2, 215, 6, 0.3)',
         borderColor: 'rgba(2, 215, 6, 0.4)',
      }]
   },
   options: {
      scales: {
         xAxes: [{
            ticks: {
               callback: function(label) {
                  return label[0];
               }
            }
         }],
         yAxes: [{
            ticks: {
               beginAtZero: true
            }
         }]
      },
      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="canvas"></canvas>

Leave a comment