简体   繁体   中英

Recharts set Y-axis value base of number displayed

Hi I'm trying to use Recharts to display some data but I have ran into a problem. The numbers I'm tying to display are too big and my Y-axis gets cut off by the webpage. Is their a way to set or customize the Y-axis values to display 10K, 10M and etc instead of 10,000 and 10,000,000 depending on the data?

在此处输入图片说明

There isn't a way to have the Y-axis to do it automatically, but if your data is being input into the recharts as ints you can add tickFormatter to the Y-axis tab. You can have tickFormatter to equal a function that takes in 1 variable which will be the Y-axis tick value (as an int) and return the number in the format you want it.

this function takes in the Y-axis as a int and returns it as a string

const DataFormater = (number) => {
  if(number > 1000000000){
    return (number/1000000000).toString() + 'B';
  }else if(number > 1000000){
    return (number/1000000).toString() + 'M';
  }else if(number > 1000){
    return (number/1000).toString() + 'K';
  }else{
    return number.toString();
  }
}

in area chart <YAxis tickFormatter={DataFormater}/>

You can also use JS standard library to achieve similar function

<YAxis tickFormatter={(value) => new Intl.NumberFormat('en', { notation: "compact" compactDisplay: "short" }).format(value)} />

new Intl.NumberFormat('en-GB', {
  notation: "compact",
  compactDisplay: "short"
}).format(987654321);
// → 988M

@CSstudent's answer is 100% correct but you don't really have to calculate those abbreviations manually. You could use js-number-abbreviate library .

This way, you could do this:

import abbreviate from "number-abbreviate";

...

<YAxis tickFormatter={abbreviate} />
 let kFormatter = (num) => {
        return Math.abs(num) > 999
         ? Math.sign(num) * (Math.abs(num) / 1000).toFixed(1) + "k"
         : Math.sign(num) * Math.abs(num);
    };
    <YAxis  dataKey="Y1" label={{ value: 'Y1'}} tickFormatter={kFormatter} />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM