Chartjs-Add \n or line break on chart.js (pie chart) labels

2👍

Reference:

How to wrap legend text in Chartjs?

let ctx = document.getElementById('myChart').getContext('2d');
let labels = [['30 students \n are feeling sick in Boys School', 'more words...'], ['10 students are feeling healthy in Boys School', 'more words...'], ['40 students are late', 'more words...'], ['20 students absent', 'more words...']];
let colorHex = ['#FB3640', '#EFCA08', '#43AA8B', '#253D5B'];

let myChart = new Chart(ctx, {
  type: 'pie',
  data: {
    datasets: [{
      data: [30, 10, 40, 20],
      backgroundColor: colorHex
    }],
    labels: labels
  },
  options: {
    responsive: true,
    legend: {
      display: false
    },
    legendCallback: function(chart) {
        var text = [];
        text.push('<ul class="' + chart.id + '-legend">');
        for (var i = 0; i < chart.data.labels.length; i++) {
            text.push('<li><span style="background-color:' + colorHex[i] + '"></span>');
            const label = chart.data.labels[i];
            text.push(Array.isArray(label) ? label.join('<br>') : label);
            text.push('</li>');
        }
        text.push('</ul>');
        return text.join('');
    }
  }
});
legend.innerHTML =  myChart.generateLegend();
#legend>ul {
  display: flex;
  justify-content: center;
}

#legend li {
  cursor: pointer;
  margin: 0px 10px;
  display: flex;
}

#legend li span {
  padding-left: 8px;
  font-family: Arial, Helvetica, sans-serif;
  font-size: 12px;
  width: 14px;
  height: 14px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script>

<div class="container">
<canvas id="myChart"></canvas>
<div id="legend"></div>
</div>

Leave a comment