Format ticks : add 'km' at the end

Hi community,

I want the plot axes tick to be formatted as ‘100km’ or ‘1000m’. I know that plotly supports D3 number formatting, there are examples of adding prefix and symbols in the documentation but I couldn’t find a way to add a postfix to the numbers.

If anyone can help me out here, I’ll be very greatful.

Thanks :slight_smile:

Hi @dataturnsmeon you can add suffix to axes ticks as follow:

fig.update_layout(
    # on the y-axis
    yaxis_ticksuffix="m",
    # on the colorbar
    coloraxis_colorbar_ticksuffix="m",
    # To specify which tick should have suffix
    yaxis_showticksuffix="all"  # or "first" or "last"
)

See the reference for more info.

You cannot have a suffix that changes for metres and kilometres but you could take advantage of the fact that D3 can do power of 1000 suffix (default behaviour for numeric ticks).

2 Likes

Thanks @RenaudLN !

@RenaudLN

Sorry to bother you again, but do you know how to replace “,” (comma) separator to “.” (dot) for thousands?
Eg: 100,000 → 100.000

In D3 we can use locale formatter but I don’t think that’s supported with plotly.

Hi @dataturnsmeon,

I am not sure if there’s an easy way to do this with D3 formatting, but I know a workaround that you can use in your python code.

In the below example I am setting the start, end and step-size for the ticks on y axis and by using string formatting I am just replacing the comma with a period.

import plotly.express as px

data_canada = px.data.gapminder().query("country == 'Canada'")
fig = px.bar(data_canada, x='year', y='pop')

t_start = 0
t_end = 35000000
t_diff = 5000000
fig.update_yaxes(
    range=[t_start, t_end],
    dtick=t_diff,
    tickvals=[x for x in range(0, t_end + t_diff, t_diff)],
    ticktext=[
        "{:,}".format(x).replace(",", ".") for x in range(0, t_end + t_diff, t_diff)
    ],
    tickmode="array",
)

fig.show()

Hope this helps :slight_smile:

1 Like

Wow ! Nice trick.
Thanks a lot @atharvakatre, this absolutely works for me.