16

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.

4 Answers4

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>
Mark
  • 106,305
  • 20
  • 172
  • 230
2

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");
jash8506
  • 51
  • 1
1

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.

abytecoder
  • 31
  • 3
0

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
  },
}
fredrivett
  • 5,419
  • 3
  • 35
  • 48