0

I tried to add \n on my pie chart labels. But it doesn't seem working. The reason why I want to add \n is because the label is quite long and break into 2 lines would be easier to read.

From the snippet I tried putting \n this on one of my labels but it seems like add more space instead of line breaking. Also, I've tried this method How do I place a new line in a label with Chart.js? but not working either. Please help...

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: {
      position: 'right'
    },
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script>

<canvas id="myChart"></canvas>
Stacie T.
  • 420
  • 6
  • 17

1 Answers1

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>
idfurw
  • 5,727
  • 2
  • 5
  • 18