Changing coloraxis when clicking button, px.choropleth_mapbox

Hi!

I’m doing a choropleth mapbox plot with a list of buttons, and I would like to be able to specify cmin and cmax for each of the buttons.

I’ve followed @empet s guide here to do my plot and it looks good so far. The only thing I need is being able to specify cmin and cmax for each of my keys in the button.

def custom_cmax(x):
    if '_House' in x:
        return 20
    else:
        return 100

buttons = []
for key in df_collection.keys():
    button = dict(method = "restyle", 
                  args = [{
                      'z': [ df_collection[key]['Percentage']],
                      'custom_data' : [[['CustPostalName', 'N']]],
                      'coloraxis' : {'cmax' : custom_cmax(key)},
                  }], 
                  label = ' '.join(key.split('_')))

    buttons.append(button)

fig = px.choropleth_mapbox(data_frame=df_collection[key],
                     geojson=geojson,
                     locations='CustPostalCdAggr',
                     featureidkey='properties.postal_code',
                     color="Percentage",
                     mapbox_style="carto-positron",
                     custom_data=['CustPostalName', 'N'],
                     zoom=5, center = {"lat": 55.676098, "lon": 12.568337})

fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})

fig.update_traces(
    hovertemplate="<br>".join([
        "<b>%{customdata[0]}</b>",
        "Percentage of customers with loan:",
        "%{z}",
        "",
        "N=%{customdata[1]}"
    ])
)

fig.update_layout(coloraxis_colorbar_thickness=23,
                  updatemenus=[dict(y=1,
                                    x=0,
                                    xanchor='right',
                                    yanchor='top',
                                    active=0,
                                    buttons=buttons)
                              ]) 

Clicking the buttons does not change the cmax and furthermore, it makes the colorbar look weird. Have someone tried this before?

Bonus info:

My df_collection.keys() looks like this:

dict_keys(['[18:20]_House', '[21:23]_House', '[24:26]_House', '[27:29]_House', '[30:32]_House', '[33:35]_House', '[18:20]_Apartment', '[21:23]_Apartment', '[24:26]_Apartment', '[27:29]_Apartment', '[30:32]_Apartment', '[33:35]_Apartment', '[18:20]_Coop', '[21:23]_Coop', '[24:26]_Coop', '[27:29]_Coop', '[30:32]_Coop', '[33:35]_Coop', '[18:20]_RD', '[21:23]_RD', '[24:26]_RD', '[27:29]_RD', '[30:32]_RD', '[33:35]_RD'])

@RockTown

coloraxis is set in layout, hence you must involve the update method, not the restyle, to be able to update both trace attributes and layout attributes. Please, download this notebook https://chart-studio.plotly.com/~empet/15605/update-method-called-within-an-update/#/, read it and run it to see how update works.

1 Like

Thank you @empet!