[Chartjs]-Shorten number labels in Charts.js

12๐Ÿ‘

โœ…

You could override the ticks.callback method as documented here: https://www.chartjs.org/docs/latest/axes/labelling.html#creating-custom-tick-formats

For example, to abbreviate the y-axis zeros to simply โ€˜Mโ€™:

var chart = new Chart(ctx, {
    type: 'line',
    data: data,
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    // Abbreviate the millions
                    callback: function(value, index, values) {
                        return value / 1e6 + 'M';
                    }
                }
            }]
        }
    }
});

My fiddle: https://jsfiddle.net/robhirstio/hsvxbjkg/17/

3๐Ÿ‘

Adding commarize feature for k, M, B and T

function commarize(min) {
  min = min || 1e3;
  // Alter numbers larger than 1k
  if (this >= min) {
    var units = ["k", "M", "B", "T"];

    var order = Math.floor(Math.log(this) / Math.log(1000));

    var unitname = units[(order - 1)];
    var num = Math.floor(this / 1000 ** order);

    // output number remainder + unitname
    return num + unitname
  }

  // return formatted original number
  return this.toLocaleString()
}

In chart JS you could use config property ticks into yAxes

var chart = new Chart(ctx, {
    type: 'line',
    data: data,
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    // Include a dollar sign in the ticks
                    callback: function(value, index, values) {
                        return String(value).commarize(); 
                    }
                }
            }]
        }
    }
});

Chart JS Reference https://www.chartjs.org/docs/latest/axes/labelling.html
Commarize reference https://gist.github.com/MartinMuzatko/1060fe584d17c7b9ca6e

2๐Ÿ‘

Support 'K', 'M', 'B':

This is my solution, to be generic when you use the same options object for multiple charts, that possibly contain lower numbers or negative numbers.

formatNumbers(value) {
  if (value >= 1000000000 || value <= -1000000000 ) {
    return value / 1e9 + 'B';
  } else if (value >= 1000000 || value <= -1000000) {
    return value / 1e6 + 'M';
  } else  if (value >= 1000 || value <= -1000) {
    return value / 1e3 + 'K';
  }
  return value;
}

My fiddle:
https://jsfiddle.net/epsilontal/v0qnsbwk/45/

Example:

enter image description here

Leave a comment