Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I place a new line in a label with Chart.js?

I have a dataset with labels using Chart.js. I want to separate the label into two lines with a new line character.

I have tried <br /> and \n, and neither work.

labels: ['(A)<br />Waking', '(B)', '(C)', '(D)'],
labels: ['(A)\nWaking', '(B)', '(C)', '(D)'], 

The first label should output like...

(A)
Waking

but it ends up looking like...

(A)<br />Waking

(A) Waking

like image 510
Kale Avatar asked Dec 01 '22 13:12

Kale


1 Answers

Looking at the docs, I can see that multiline labels are possible.

Updated link to documentation: https://www.chartjs.org/docs/latest/general/data-structures.html

I looked at the source code of an example and for multiline labels, they have each multiline in an array where each element of the array is rendered in its own line.

For example:

labels: [['(A)', 'Waking'], '(B)', '(C)', '(D)'],

See DEMO below:

var randomScalingFactor = function() {
  return Math.round(Math.random() * 100);
};

window.chartColors = {
    red: 'rgb(255, 99, 132)',
    orange: 'rgb(255, 159, 64)',
    yellow: 'rgb(255, 205, 86)',
    green: 'rgb(75, 192, 192)',
    blue: 'rgb(54, 162, 235)',
    purple: 'rgb(153, 102, 255)',
    grey: 'rgb(201, 203, 207)'
};

var config = {
  type: 'line',
  data: {
    labels: [
      ['(A)', 'Walking'], '(B)', '(C)', '(D)'],
    datasets: [{
      label: 'My First dataset',
      fill: false,
      backgroundColor: window.chartColors.red,
      borderColor: window.chartColors.red,
      data: [
        randomScalingFactor(),
        randomScalingFactor(),
        randomScalingFactor(),
        randomScalingFactor()        
      ]
    }, {
      label: 'My Second dataset',
      fill: false,
      backgroundColor: window.chartColors.blue,
      borderColor: window.chartColors.blue,
      data: [
        randomScalingFactor(),
        randomScalingFactor(),
        randomScalingFactor(),
        randomScalingFactor()
      ],
    }]
  },
  options: {
    responsive: true,
    title: {
      display: true,
      text: 'Chart with Multiline Labels'
    },
  }
};

window.onload = function() {
  var ctx = document.getElementById('canvas').getContext('2d');
  window.myLine = new Chart(ctx, config);
};
<script src="https://www.chartjs.org/dist/2.8.0/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://ajax.cloudflare.com/cdn-cgi/scripts/a2bd7673/cloudflare-static/rocket-loader.min.js" data-cf-settings="100752039a7e60f6a2c8f47d-|49"></script>

<div style="width:90%;">
  <canvas id="canvas"></canvas>
</div>
like image 147
blurfus Avatar answered Dec 06 '22 01:12

blurfus