admin管理员组

文章数量:1199961

I want to format Y-axis data in D3 Line chart. It's about world population so that is quite large.

I am currently using below code, which is showing "G" instead of "B".

d3.format("s")

I researched and found that here "G" stands of Giga, is there a way to change it to B which denotes Billion?

Thanks.

I want to format Y-axis data in D3 Line chart. It's about world population so that is quite large.

I am currently using below code, which is showing "G" instead of "B".

d3.format("s")

I researched and found that here "G" stands of Giga, is there a way to change it to B which denotes Billion?

Thanks.

Share Improve this question asked Nov 23, 2016 at 21:47 Rashmit Dalbir SinghRashmit Dalbir Singh 1731 silver badge5 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 12

If you like the formatting of SI-prefix, but not the actual prefix, just swap it out with a simple .replace:

var f = d3.format("0.2s");

document.write(
  f(1e9).replace(/G/,"B")
);
<script src="https://d3js.org/d3.v4.min.js"></script>

If you don't want to override the library globally, but you want to use your "B" function around the place the same way as d3.format:

import { format } from 'd3-format';
export const formatBillions = fs => s => format(fs)(s).replace(/G/, "B");

For those needing this with plotly.js (which uses d3 under the hood), you can provide the exponentformat to the axis, as well as optional tickprefix, should you want tick formats to be $1B not $1G) (see types for details of values exponentformat accepts):

import { Layout } from "plotly.js";

const layout: Partial<Layout> = {
  xaxis: {
    ... // your other layout values
    tickprefix: "$", // use manual prefix as we can't use `tickformat` w/ `exponentformat`
    exponentformat: "B", // use billions not giga
  },
}

If you want to apply Mark's Answer Globally, I used the following

fcopy = d3.format;
function myFormat(){ 
         function_ret = fcopy.apply(d3, arguments) 
         return (function(args){return function (){ 
                return args.apply(d3, arguments).replace(/G/, "B");
         }})(function_ret) 
} 
d3.format = myFormat;

I had the same problem with Superset, I added this in the static/dashboard file.

本文标签: javascriptD3 Formatting tick value To show B (Billion) instead of G (Giga)Stack Overflow