Update colorbar/coloraxis position

Hello community,

I’m trying to update the position of a colobar/axis from a Choropleth map.

I found on the forum that it was possible to do it with the following line, but nothing happened for me:

fig.update_layout(coloraxis_colorbar_x=-0.15)

I also tried this:

fig.data[0].colorbar.x=-0.1

It’s almost working with this method, but when I clicked on my button, the colorbar is going back to it’s original position (on the right).

Here is my code:

import numpy as np
import plotly.graph_objects as go

df = pd.DataFrame(np.array([['Germany', 2, 3], ['United States', 5, 6], ["Italy", 8, 9]]),
                   columns=['country', 'data_a', 'data_b'])

fig = go.Figure(data=go.Choropleth(
    locations = df['country'],
    z = df['data_a'],
    text = df['country'],
    colorscale = 'Teal',
    autocolorscale=False,
    reversescale=False,
    marker_line_color='black',
    marker_line_width=0.3,
    colorbar_title = '<b>data_a_title</b>',
    locationmode ='country names'
))

#update map style
fig.update_layout(
    geo=dict(
        showframe=False,
        showcoastlines=True,
        projection_type='equirectangular'
    )
)
 

#dropdown menu
button1 =  dict(method = "update",
                args = [{'z': [ df["data_a"] ] },
                       {"colorbar":{"title":"data_a_title"}}],
                label = "data_a")
button2 =  dict(method = "update",
                args = [{'z': [ df["data_b"] ]},
                       {"colorbar_title":'data_b_title'}],
                label = "data_b")


fig.update_layout(width=700,
                  coloraxis_colorbar_thickness=23,
                  updatemenus=[dict(y=0.2,
                                    x=1,
                                    xanchor='right',
                                    yanchor='bottom',
                                    active=0,
                                    buttons=[button1, button2])
                              ]) 

fig.show(config={"displayModeBar": False, "showTips": False})

I have been trying several things around the args to keep the same position like but nothing worked so far.

Any idea about how to do it?

Thank you

I found the solution. To keep the same position when clicking on the button. Be sure to add the following line to set the original position:

fig.data[0].colorbar.x=-0.1

And regarding the button update, you will need to set the new x position like this:

button1 =  dict(method = "update",
                args = [{'z': [ df["data_a"] ] ,
                       "colorbar":{"title":{"text":"title_a"}, 'x':-0.1 }}],
                label = "data_a")
button2 =  dict(method = "update",
                args = [{'z': [ df["data_b"] ],
                       "colorbar":{"title":{"text":"title_b"}, 'x':-0.1 }}],
                label = "data_b")
1 Like