Can we show long numbers as 1k, 1M, 1B on axis in charts?

👍:0

Welcome to SO.

Yes that’s possible. Adding here an example shorten method which actually does what you asked for, you can improve it as per your need. The configuration for y-axis by passing a callback for tick field solves it. Hope that helps.

function shorten(n, d) {
  if (n < 1000) {
    return n + '';
  }
  if (n > 1e7) {
    return "10M+"
  }
  var x = ('' + n).length;
  var p = Math.pow;
  d = p(10, d);
  x -= x % 3;
  return Math.round(n * d / p(10, x)) / d + " KMBTPE" [x / 3];
}

const chartInstance = new Chart(ctx, {
  type: 'line',
  data: props.data,
  options: {
    scales: {
      yAxes: [{
        ticks: {
          callback(value, index, values) {
            return shorten(value, 1);
          }
        },
      }],
    },
  },
});

Leave a comment