Format linear scale large number replace G to B

Viewed 89

I'm trying to format a linear scale of a d3 chart. My y-scale are usually in the billions. I use below code:

 const yAxis = g => g
.attr("transform", `translate(${margin.left},0)`)
.call(axisLeft(y).ticks(10).tickFormat(format(".2s")))

But this gives me units in 'G' instead of 'B' when my y-axis goes into billions. See screenshot

So I replaced the last line of my code with this:

    .call(axisLeft(y).ticks(10).tickFormat(format(".2s").replace("G","B")))

But I got a typeError: ×

TypeError: Object(...)(...).replace is not a function

I also tried this:

    .call(axisLeft(y).ticks(10).tickFormat((d, i)=>format(".2s")(data[i].value).replace("G", "B")))

But my ticks become no longer 'nice()' and the order is all messed up.

enter image description here

How can I replace my unit from 'G' to 'B'? Thanks.

1 Answers

That format("2s") is a function that returns a string, while replace should be called on the string itself.

Therefore, it should be:

.call(axisLeft(y).ticks(10).tickFormat(d => format(".2s")(d).replace("G","B")))

Here, format(".2s")(d) returns the formatted string according to the tick. Finally, your second snippet almost got it right, but you're ignoring the actual scale-generated ticks by using only the ticks' indices to get the data values.

Related