charts icon indicating copy to clipboard operation
charts copied to clipboard

Feature request: option to define a y axis label formatter

Open mathiasbynens opened this issue 4 years ago • 6 comments

I’m creating a chart with values in the hundreds of thousands range. Currently the Y axis labels look like this:

300000
200000
100000

I’d love to be able to define a formatter so that I could, for example, group the numbers per thousands:

300,000
200,000
100,000

...or using short notation:

300K
200K
100K

Note that this is very similar to the tooltip formatters that are already supported — just that the formatter would be applied on the Y axis labels.

(Here's the chart I'm talking about, in case it helps to understand my use case: https://mathiasbynens.github.io/covid-19-vaccinations-germany/)

mathiasbynens avatar Jan 12 '21 15:01 mathiasbynens

I’ve implemented this horrible, horrible workaround:

  // Work around https://github.com/frappe/charts/issues/322.
  const fixLabels = () => {
    const compactFormatter = new Intl.NumberFormat('en', {
      notation: 'compact',
    });
    const labels = document.querySelectorAll('text[x="-10"]');
    for (const label of labels) {
      const number = Number(label.textContent);
      label.textContent = compactFormatter.format(number);
    }
  };

  // TODO: Use a mutation observer instead, if we can find a reliably
  // detectable DOM modification that signals the charts are fully
  // rendered.
  setTimeout(() => {
    fixLabels();
  }, 1000);

mathiasbynens avatar Apr 30 '21 06:04 mathiasbynens

There's an axis option to shorten these.

Can be used as follows

const chart = new Chart("#app", {
  data: financialData,
  type: "line",
  axisOptions: {
    shortenYAxisNumbers: true,
  },
});

scmmishra avatar May 07 '21 08:05 scmmishra

@mathiasbynens I've created a PR on your project to enable this behaviour, you can check it out.

I have another suggestion I've highlighted in the issue here It has instructions to upgrade to v2 beta if you wish to do that

scmmishra avatar May 07 '21 09:05 scmmishra

Thanks!

I didn’t know about this setting — would it be worth adding it to the docs?

mathiasbynens avatar May 09 '21 05:05 mathiasbynens

Hi! Aside from "shortenYAxisNumbers", will there be a simple "append" option where I could add text like "%" or "pts"? thanks!

markjohnson4 avatar Nov 12 '21 22:11 markjohnson4

Just shortenYAxisNumbers is not enough. An option to provide a formatter function is mandatory. The library only understands how to represent numbers, but there are some values that are better represented with strings for readabilty, for example big series 1k 20k, pixels 2k 4k 8k, milliseconds/seconds/minutes properly formatted 1hour 2hour 3hour or 1day 2day 1week etc. This library is tinny and awesome, but not being able to properly format the Y axis is a deal breaker

danielo515 avatar Jan 28 '22 17:01 danielo515