Cannot relayout mapbox_style with button

I have created a code based on the sample in the reference for your assignment. It seems that the map box needs to be configured not only for style but also for other necessary settings. The update method is relayout, as shown in the reference.

import plotly.express as px

df = px.data.election()
geojson = px.data.election_geojson()

fig = px.choropleth_mapbox(df,
                           geojson=geojson,
                           color="Bergeron",
                           locations="district",
                           featureidkey="properties.district",
                           center={"lat": 45.5517, "lon": -73.7073},
                           #mapbox_style="carto-positron",
                           zoom=9
                          )
# fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})

fig.update_layout(dict(mapbox_style='open-street-map'))
fig.update_layout(
    updatemenus=[
        dict(
            type="buttons",
            direction='down',
            buttons=[
                dict(label="Margin 1",
                     method="relayout",
                     args=[{'margin': dict(l=100, r=200, t=50, b=50)}]),
                dict(label="Margin 2",
                     method="relayout",
                     args=[{'margin': dict(l=0, r=0, t=0, b=0)}]),
                dict(label="Mapbox",
                     method="relayout",
                     args=[{"mapbox": {"style":'carto-darkmatter', 
                            "center": {"lat": 45.5517, "lon": -73.7073},
                            "zoom": 9}}
                          ]),
                dict(label="Margin and Mapbox",
                     method="relayout",
                     args=[{"mapbox": {"style": 'carto-darkmatter',
                                       "center": {"lat": 45.5517, "lon": -73.7073},
                                       "zoom": 9},
                            'margin': dict(l=0, r=0, t=60, b=0)}]),
            ],
        )
    ]
)
fig.show()

1 Like