[Chartjs]-How to shorten Chart.js label

3👍

This answer reference from post.On mouse hover you can see tooltip showing full label name

var options = {
  scales: {
    xAxes: [{
      ticks: {
        callback: function(value) {
          if (value.length > 4) {
            return value.substr(0, 4) + '...'; //truncate
          } else {
            return value
          }

        },
      }
    }],
    yAxes: [{}]
  },
  tooltips: {
    enabled: true,
    mode: 'label',
    callbacks: {
      title: function(tooltipItems, data) {
        var idx = tooltipItems[0].index;
        return 'Title:' + data.labels[idx]; //do something with title
      },
      label: function(tooltipItems, data) {
        //var idx = tooltipItems.index;
        //return data.labels[idx] + ' €';
        return tooltipItems.xLabel + ' €';
      }
    }
  },
};


var ctx = document.getElementById("myCanvas1");
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ["Red", "Blue mbkjbjkbjlkbk", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      backgroundColor: [
        'rgba(255, 99, 132, 0.2)',
        'rgba(54, 162, 235, 0.2)',
        'rgba(255, 206, 86, 0.2)',
        'rgba(75, 192, 192, 0.2)',
        'rgba(153, 102, 255, 0.2)',
        'rgba(255, 159, 64, 0.2)'
      ],
      borderColor: [
        'rgba(255,99,132,1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
        'rgba(75, 192, 192, 1)',
        'rgba(153, 102, 255, 1)',
        'rgba(255, 159, 64, 1)'
      ],
      borderWidth: 1
    }]
  },
  options: options
});


var ctx = document.getElementById("myCanvas2");
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      backgroundColor: [
        'rgba(255, 99, 132, 0.2)',
        'rgba(54, 162, 235, 0.2)',
        'rgba(255, 206, 86, 0.2)',
        'rgba(75, 192, 192, 0.2)',
        'rgba(153, 102, 255, 0.2)',
        'rgba(255, 159, 64, 0.2)'
      ],
      borderColor: [
        'rgba(255,99,132,1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
        'rgba(75, 192, 192, 1)',
        'rgba(153, 102, 255, 1)',
        'rgba(255, 159, 64, 1)'
      ],
      borderWidth: 1
    }]
  },
  options: options
});
div {
  display: inline-block;
  width: 49%;
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>

<body>
  <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.js"></script>
  <div>
    <canvas id="myCanvas1"></canvas>
  </div>
  <div>
    <canvas id="myCanvas2"></canvas>
  </div>
</body>

</html>

Leave a comment