[Chartjs]-Make Chart.js horizontal bar labels multi-line

16👍

You can use the following chart plugin :

plugins: [{
   beforeInit: function(chart) {
      chart.data.labels.forEach(function(e, i, a) {
         if (/\n/.test(e)) {
            a[i] = e.split(/\n/);
         }
      });
   }
}]

add this followed by your chart options

ᴜꜱᴀɢᴇ :

add a new line character (\n) to your label, wherever you wish to add a line break.

ᴅᴇᴍᴏ

var chart = new Chart(ctx, {
   type: 'horizontalBar',
   data: {
      labels: ['Jan\n2017', 'Feb', 'Mar', 'Apr'],
      datasets: [{
         label: 'BAR',
         data: [1, 2, 3, 4],
         backgroundColor: 'rgba(0, 119, 290, 0.7)'
      }]
   },
   options: {
      scales: {
         xAxes: [{
            ticks: {
               beginAtZero: true
            }
         }]
      }
   },
   plugins: [{
      beforeInit: function(chart) {
         chart.data.labels.forEach(function(e, i, a) {
            if (/\n/.test(e)) {
               a[i] = e.split(/\n/);
            }
         });
      }
   }]
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="ctx"></canvas>

21👍

If you want to have full control over how long labels are broken down across lines you can specify the breaking point by providing labels in a nested array. For example:

var chart = new Chart(ctx, {
...
  data: {
    labels: [["Label1 Line1:","Label1 Line2"],["Label2 Line1","Label2 Line2"]],
    datasets: [{
...
});

0👍

Unfortunately provided answers work only with static data, so I wrote simple JS function specificallly for dynamic texts, it splits label into arrays with defined line length limit:

function splitLabelForChart(label) {
  const words = label.split(' ');
  const lineLimit = 14;
  const lines = [];

  let line = '';
  let currentWordIdx = 0;

  while (currentWordIdx < words.length) {
    if (line.length + words[currentWordIdx].length < lineLimit) {
      line += `${words[currentWordIdx]} `;
      currentWordIdx++;

      if (currentWordIdx === words.length) {
        lines.push(line);
      }
    } else {
      if (line.length) {
        lines.push(line);
        line = '';
      }

      if (words[currentWordIdx].length >= lineLimit) {
        lines.push([words.currentWord]);
        currentWordIdx++;
      }
    }
  }

  return lines;
}

And how it’s used:

const chartData = {
    labels: data.map((e) => splitLabelForChart(e.label)),
    datasets: [
      ...
    ],
  };

Leave a comment