Plotly.py: Force axis units to thousands (k) instead of millions (M)

Viewed 3512

Since the numbers on my x axis are somewhat large, they are showing in millions (i.e., 25.8512M). However, I would like to force the format to show in thousands instead (i.e., 25,851.2k).

import plotly.graph_objects as go

fig = go.Figure(data = [go.Scatter(x = [25.851e6, 25.852e6], y = [0, 1])])
    
fig.show()

enter image description here

Following the suggestions in this SO question and this d-3 format API reference, I have tried setting the axis tickformat to ',.6s', for example, but no luck.

Any suggestions?

1 Answers

It appears there is no way to accomplish what you want in Plotly (look at this similar question asking to format billions 'B' as millions 'M')

The best solution I could come up with is to convert your data from millions to thousands, add the letter 'k', and use this list of strings as tickvalues. Not very elegant, but hopefully it accomplishes what you want.

import plotly.graph_objects as go

vals_in_millions = [25.851e6, 25.852e6]
fig = go.Figure(data = [go.Scatter(x = vals_in_millions, y = [0, 1])])

def convert_million_to_thousands(values):
    return [str(num/1000)+'k' for num in values]

fig.update_layout(
    xaxis = dict(
        tickmode = 'array',
        tickvals = vals_in_millions,
        ticktext = convert_million_to_thousands(vals_in_millions)
    )
)

fig.show()

enter image description here

Related