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:

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

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(spot_monthly.data)['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(spot_monthly.data)['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": {{ data.map((i) => 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

1 Like

Yes, you can use texttemplate to format the values dynamically. Try something like this:

javascript

texttemplate: "%{value:.1f}B"

For dynamic scaling between Billions (B) and Millions (M), you can use a custom function in the texttemplate, such as:

template

texttemplate: %{customdata}

Then preprocess your data to return formatted strings like '17.6B' or '950M' based on the value.

On a related note, handling large-value formatting clearly is something we also prioritize in Unibee, especially when displaying usage-based analytics to customers.

Hope that helps!

1 Like

Thanks for the help on this @Ba_Gen!

It looks like this post was for our now deprecated older version of the chart component.

With the new v2 bar chart component, you can add in the code snippet you shared into this input field in the spot I show in my screenshot below.