charts
charts copied to clipboard
Feature request: option to define a y axis label formatter
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/)
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);
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,
},
});
@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
Hi! Aside from "shortenYAxisNumbers", will there be a simple "append" option where I could add text like "%" or "pts"? thanks!
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