Chart.js: Logarithmic chart defaults axis values to scientific format (i.e. 5e+2). But it is not clear how to change the number format.

Created on 9 Aug 2016  路  7Comments  路  Source: chartjs/Chart.js

Created logarithmic chart using:

options = {
        scales: {
            xAxes: [{
                type: 'linear',
                position: 'bottom'
            }],
            yAxes: [{
                type: 'logarithmic',
                position: 'left'
            }]
        }
    }                 

This automatically changes the axis values to scientific format. (I don't think this is desired behavior.) I searched through the docs and could not figure out how to set the axis values to regular format (i.e. 100000). Or even better: 100,000.

Googling I found the custom Javascript formatter callback function, but that doesn't seem like a good solution.

How to set the axis values (labels) format?

support

Most helpful comment

In the current version of ChartJS you loose the log scale, with this implementation all works as expected.

callback: function(...args) {
  const value = ChartJS.Ticks.formatters.logarithmic.call(this, ...args);
  if (value.length) {
    return Number(value).toLocaleString()
  }
  return value;
}

All 7 comments

The callback function is the way to do this. It transforms the numeric values intro strings. The default implementation uses scientific notation https://github.com/chartjs/Chart.js/blob/master/src/scales/scale.logarithmic.js#L12-L19

You can specify a callback in your options for each chart or you can update the default by doing

Chart.scaleService.updateScaleDefaults('logarithmic', {
  ticks: {
    callback: function(tick, index, ticks) {
      // new default function here
    }
  }
});

OK, thanks for the help.

It seems that this will convert to a more human readable format:

return tick.toLocaleString()

In the current version of ChartJS you loose the log scale, with this implementation all works as expected.

callback: function(...args) {
  const value = ChartJS.Ticks.formatters.logarithmic.call(this, ...args);
  if (value.length) {
    return Number(value).toLocaleString()
  }
  return value;
}

Hi! The above worked great for me, except that I had to change this line:

const value = ChartJS.Ticks.formatters.logarithmic.call(this, ...args);

with

const value = Chart.Ticks.formatters.logarithmic.call(this, ...args);

So ChartJS is replaced with Chart (took me a short while to figure it out, I hope this helps others).

In Chart.js 3.0 the log chart no longer defaults to scientific format

the chart becomes linear in 3.0.0, while it is logarithmic in 2.9.3

the chart becomes linear in 3.0.0, while it is logarithmic in 2.9.3

Did you migrate the scale configuration?
https://www.chartjs.org/docs/next/getting-started/v3-migration

Was this page helpful?
0 / 5 - 0 ratings