更新 colorbar/coloraxis 位置 - Plotly Python

Update colorbar/coloraxis position - Plotly Python

我正在尝试从 Choropleth 地图更新 colobar/axis 的位置。

我在 plotly 论坛上发现可以使用以下行来完成,但我没有任何反应:

fig.update_layout(coloraxis_colorbar_x=-0.15)

我也试过这个:

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

使用这种方法几乎可以正常工作,但是当我点击我的更新按钮时,颜色条会回到原来的位置(很明显在右边)。

这是我的代码:

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":{"text":"title_a"} }}],
                label = "data_a")
button2 =  dict(method = "update",
                args = [{'z': [ df["data_b"] ],
                       "colorbar":{"title":{"text":"title_b"} }}],
                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})

我一直在围绕 args 尝试一些方法来保持相同的位置,但到目前为止没有任何效果。

知道怎么做吗?

谢谢

我找到了解决方案。单击按钮时保持相同的位置。请务必添加以下行以设置原始位置:

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

关于按钮更新,您需要像这样设置新的 x 位置:

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")