How to display kb, mb, gb, tb in chart.js tooltip?

Member

by shyann , in category: Javascript , 6 months ago

How to display kb, mb, gb, tb in chart.js tooltip?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by darrion.kuhn , 6 months ago

@shyann 

To display the values of kb, mb, gb, tb in the tooltip using Chart.js, you can use the tooltips property in the options of the chart configuration. You can create a custom tooltip callback function that formats the tooltip label with the appropriate units.


Here is an example code snippet to demonstrate how to display values with various units 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
var chartData = {
  labels: ["January", "February", "March", "April", "May", "June", "July"],
  datasets: [{
    label: 'Data Usage',
    data: [1000, 2000, 3000, 4000, 5000, 6000, 7000],
    borderWidth: 1
  }]
};

var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
  type: 'line',
  data: chartData,
  options: {
    tooltips: {
      enabled: true,
      mode: 'index',
      callbacks: {
        label: function(tooltipItem, data) {
          var dataset = data.datasets[tooltipItem.datasetIndex];
          var value = dataset.data[tooltipItem.index];
          
          if(value >= 1024 && value < 1048576) {
            return value/1024 + ' KB';
          } else if(value >= 1048576 && value < 1073741824) {
            return value/1048576 + ' MB';
          } else if(value >= 1073741824 && value < 1099511627776) {
            return value/1073741824 + ' GB';
          } else {
            return value/1099511627776 + ' TB';
          }
        }
      }
    }
  }
});


In this code snippet, the tooltip callback function checks the value of the data point in the tooltip and formats it with appropriate units depending on its magnitude. You can customize this function further to match your specific needs.