Search code examples
jupyter-notebookplotlyvisualizationdropdown

plotly drop down menu map issues


Issues with my drop down menu. The values in the map don not match with the values I need them to match with. For example, if the drop down value is Number of deaths, the value in the map is death rate.The image should be showing the number of deaths for each countries, but is showing the death rate.

enter image description here

# three columns we're going to build choropleths from
cols = ['Number of Deaths', 'Death Rate Per 100,000']

# build figures for each of the required columns
# key technique is append a suffix to animation frame so each frame has it's
# own name...
figs = [
    px.choropleth(
        data_frame=Global_Burden_of_Disease_df_country,
        locations='Country Name',
        locationmode='country names',
        color=c,
        title='Choropleth Map Example',
        hover_name="Country Name",  # identify country code column
        animation_frame="Year",  # identify date column
        projection="equirectangular",  # select projection
        color_continuous_scale=color,  # select prefer color scale
    )
    for c, color in zip( cols, ["Blues", 'Reds'])
]


# play / pause don't work as don't stop between columns..
layout = {
    k: v
    for k, v in figs[0].to_dict()["layout"].items()
    if k not in ["template", "updatemenus"]
}


# build figure from all frames, with layout excluding play/pause buttons
fig = go.Figure(
    data=figs[0].data, frames=[fr for f in figs for fr in f.frames], layout=layout
)

# finally build drop down menu...
fig = fig.update_layout(
    updatemenus=[
        {
            "buttons": [
                {
                    "label": c,
                    "method": "relayout",
                    "args": [
                        {
                            "coloraxis": col_fig.layout.coloraxis,
                            "sliders": col_fig.layout.sliders,
                        }
                    ],
                }
                for c, col_fig in zip(cols, figs)
            ]
        }
    ]
)

fig

I am trying to create a map, that shows different values based on the year in the drop down menu. The values are from a dataframe.


Solution

  • You need to ensure update each time either dropdown values of slider values are chosen:

    import plotly.express as px
    import plotly.graph_objects as go
    import pandas as pd
    
    data = {
        "Country Name": ["France", "Germany", "Sweden"] * 4,
        "Year": [2000, 2000, 2000, 2005, 2005, 2005, 2010, 2010, 2010, 2015, 2015, 2015],
        "Number of Deaths": [100, 150, 200, 110, 160, 210, 120, 170, 220, 130, 180, 230],
        "Death Rate Per 100,000": [10, 15, 20, 11, 16, 21, 12, 17, 22, 13, 18, 23],
    }
    
    Global_Burden_of_Disease_df_country = pd.DataFrame(data)
    
    cols = ['Number of Deaths', 'Death Rate Per 100,000']
    
    figs = []
    frames = []
    
    for c, color in zip(cols, ["Blues", 'Reds']):
        fig = px.choropleth(
            data_frame=Global_Burden_of_Disease_df_country,
            locations='Country Name',
            locationmode='country names',
            color=c,
            hover_name="Country Name",
            animation_frame="Year",
            projection="equirectangular",
            color_continuous_scale=color,
        )
        fig.update_layout(coloraxis_colorbar_title=c)
        figs.append(fig)
        
        for frame in fig.frames:
            frame['name'] = f"{c}_{frame['name']}"
            frames.append(frame)
    
    layout = {
        k: v
        for k, v in figs[0].to_dict()["layout"].items()
        if k not in ["template", "updatemenus"]
    }
    
    fig = go.Figure(data=figs[0].data, layout=layout)
    fig.frames = frames
    
    frames_dict = {c: [f for f in frames if f['name'].startswith(c)] for c in cols}
    
    dropdown_buttons = [
        {
            "label": c,
            "method": "animate",
            "args": [
                [f"{c}_{year}" for year in Global_Burden_of_Disease_df_country['Year'].unique()],
                {
                    "mode": "immediate",
                    "frame": {"duration": 500, "redraw": True},
                    "transition": {"duration": 0},
                }
            ],
        }
        for c in cols
    ]
    
    fig.update_layout(
        updatemenus=[
            {
                "buttons": dropdown_buttons,
                "direction": "down",
                "showactive": True,
            }
        ],
        coloraxis_colorbar_title=cols[0],  
        title={"text": f"Choropleth Map - {cols[0]}"}, 
    )
    
    fig.show()
    
    

    enter image description here enter image description here enter image description here