How to change the label and value like 500,000 to 500k in chart.js?

Member

by aubrey , in category: Javascript , 10 months ago

How to change the label and value like 500,000 to 500k in chart.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by dedrick , 10 months ago

@aubrey 

To change the label and value format in chart.js, you can use the "callback" function provided by the chart.js library. This function allows you to manipulate the label or value before it is displayed on the chart.


Here's an example of how to change the label format from "500,000" to "500k" using the "callback" function:

 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
var chartOptions = {
  scales: {
    y: {
      ticks: {
        callback: function (value, index, values) {
          if (value >= 1000) {
            return (value / 1000) + 'k';
          }
          return value;
        }
      }
    }
  }
};

// Example data
var data = {
  labels: ["January", "February", "March"],
  datasets: [{
    data: [500000, 750000, 1000000]
  }]
};

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


In this example, we are defining a new "callback" function inside the "ticks" options for the y-axis. This function checks if the value is greater than or equal to 1000. If it is, it divides the value by 1000 and appends the 'k' suffix to represent thousands. Otherwise, it returns the original value.


You can customize this function to suit your specific formatting needs.