[Chartjs]-Chart.js tooltip values display in two lines

6👍

You cannot use new-line (\n) character or ES6 syntax for that matter (as canvas/chart.js doesn’t support it).

Instead, you should use the afterLabel callback function of tooltips, which returns a text to render after an individual label.

Example

var chart = new Chart(ctx, {
   type: 'line',
   data: {
      labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
      datasets: [{
         label: 'LINE',
         data: [3, 1, 4, 2, 5],
         backgroundColor: 'rgba(0, 119, 290, 0.2)',
         borderColor: 'rgba(0, 119, 290, 0.6)'
      }]
   },
   options: {
      tooltips: {
         callbacks: {
            label: function(tooltipItem, data) {
               var someValue = "Hello";
               return someValue;
            },
            afterLabel: function(tooltipItem, data) {
               var someValue2 = "Mindfuc";
               return someValue2;
            }
         }
      }
   }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.0/Chart.min.js"></script>
<canvas id="ctx"></canvas>

2👍

This worked for me. Just simply return an array of strings as labels in tooltips callbacks.

 tooltips: {
    callbacks: {
      label: function(tooltipItem, data) {
        let label = "Line 1";
        let label2 = "Line 2";
        return [label, label2];
      }
    }
  }

0👍

there are also other options how to split two lines in chart js tooltips:

  1. By default, values are separated if provided in an array (source), so in your case you could try:

    return [someValue, someValue2];
    
  2. Or alternatively, you can use split (source):

    return (someValue + "/n" + someValue2).split('\n');
    

Both options should provide same result.

Leave a comment