How to append more data in tooltip of graph in chart.js?

by edmond_brakus , in category: Javascript , 10 months ago

How to append more data in tooltip of graph in chart.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by hal.littel , 10 months ago

@edmond_brakus 

To append more data to the tooltip in Chart.js, you can make use of the tooltip's callbacks option.


Here's an example of appending more data in the tooltip:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
var chartData = {
  labels: ['January', 'February', 'March', 'April', 'May'],
  datasets: [
    {
      label: 'Data 1',
      data: [10, 20, 30, 40, 50],
      backgroundColor: 'rgba(255, 99, 132, 0.2)',
      borderColor: 'rgba(255, 99, 132, 1)',
      borderWidth: 1
    },
    {
      label: 'Data 2',
      data: [5, 10, 15, 20, 25],
      backgroundColor: 'rgba(54, 162, 235, 0.2)',
      borderColor: 'rgba(54, 162, 235, 1)',
      borderWidth: 1
    }
  ]
};

var chartOptions = {
  tooltips: {
    callbacks: {
      label: function(tooltipItem, data) {
        var datasetLabel = data.datasets[tooltipItem.datasetIndex].label || '';
        var value = tooltipItem.yLabel;
        
        // Add more data to the tooltip
        var moreData = 'Some extra data: ' + value * 2;
        
        return datasetLabel + ': ' + value + ' ' + moreData;
      }
    }
  }
};

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'bar',
  data: chartData,
  options: chartOptions
});


In the above example, the label callback function is used to append more data to the tooltip. The tooltipItem parameter is used to access the current tooltip data, and the data parameter is used to access the chart data.


In this example, the moreData variable is appended to the tooltip, which is calculated as double the value (value * 2).


You can modify the moreData variable as per your requirements, and include any additional data you want to display in the tooltip.