Plotly Math for Labels (Billions, Millions, etc.)

I have a bar chart where each month has a value in the billions. Is there a way to format the labels to show this value in billions, with a "B" label?

E.g., August's value is 17610171495, but I would like to show it as 17.6B, just like the how it displays when I hover over the bar.

Is there a way to use "texttemplate" to do this? Is there a way to dynamically have it show the value in either B (billions) or M (millions)? Below is the current code I have for the labels:

    "text": {{formatDataAsObject(['Kraken Spot']}},
    "textposition": "outside",
    "textfont": {"color":'#000000', "size":10},
    "texttemplate": "%{text:.1f}",   

Currently, I can use a work-around where in my dataset, I add an additional column just for the labels. E.g., column 1 is the actual value of 17610171495, and column 2 for labels is 17.610171495

1 Like

Hey @Oxbeanz!

With some JavaScript you can transform your data before passing it to the text property in plotly. Something like the following might work:

"text": {{ formatDataAsObject(['Kraken Spot'].map(data => data / 10**9 + "B") }}

If you'd like for it to only have a certain number of digits past the decimal you can use .toFixed:

"text": {{ formatDataAsObject(['Kraken Spot'].map(data => (data / 10**9).toFixed(1) + "B") }}

Does that accomplish what you're looking for?

1 Like

I've built a different (better?) way to do this:

"text": {{ => Intl.NumberFormat("en",{notation: "compact",minimumFractionDigits:1,maximumFractionDigits: 1}).format( i )) }}

This would take care of millions, billions, or thousands, and it is easy to adjust the number of digits past the decimal point