Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ChartJS - Set different hover-text than x-axis description

I'm using chartjs to visualize some data in a bar diagram. The labels are quite long, so I cut them. However, I'd like to have the text for the tooltips (on hover) to be the original one. Can I achieve this with the default chartjs configuration?

I use the following to generate the charts:

function DrawChart(canvasID, remoteFields, remoteData, remoteColors, remoteBorderColors) {
    var ctx = document.getElementById(canvasID).getContext('2d');

    var orig = remoteFields;
    var maxLabelLength = 20;
    for(var i = 0; i < remoteFields.length; i++) {
        if(remoteFields[i].length > maxLabelLength) {
            remoteFields[i] = remoteFields[i].substring(0,maxLabelLength) + "...";
        }
    }
    var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
    labels: remoteFields,
        datasets: [{
            data: remoteData,
            backgroundColor: remoteColors,
            borderColor: remoteBorderColors,
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero:true,
                    stepSize: 1
                }
            }]
        },
        responsive: true,
        maintainAspectRatio: false,
        legend: {
        display: false
    }
    }
});
}
like image 791
Marcel Avatar asked Jun 04 '17 14:06

Marcel


1 Answers

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>
like image 193
ɢʀᴜɴᴛ Avatar answered Oct 10 '22 09:10

ɢʀᴜɴᴛ