Trouble with the dcc.Dropdown() using multiple inputs

Hello All !,
I am a beginner and get stuck with the following,
I see that data frame inside callback function remains empty, so there is no graph displayed.
I cannot figure out why dataframe that results from filters in empty…
Would you have any idea/suggestion ?

Many thanks for help !

print(f'df.head(): {df.head()}')
print(f'nb rows: {len(df)}')

app = dash.Dash()

app.layout = html.Div([
    html.Div([dcc.Dropdown(options=df['continent'].unique(), value='Asia', id='select-continent'),
              
              dcc.Dropdown(options=df['country'].unique(), value='Afghanistan', id='select-country'),
              
              dcc.Graph(id='lifeexp-gdp')
              ]
             )
    ]
    )

@callback(
    Output(component_id='lifeexp-gdp', component_property='figure'),
    
    [Input(component_id='select-country', component_property='value'),
    Input(component_id='select-continent', component_property='value')]
    )
def fn_sortie(selected_continent, selected_country):
    df_selected_continent = df[df['continent'] == selected_continent]
    df_selected_country = df_selected_continent[df_selected_continent['country'] == selected_country]
    
    print(f'len(df): {len(df_selected_country)}')
    
    fig = px.scatter(df_selected_country, x='gdpPercap', y='lifeExp', 
                      size='pop', color='country', hover_name='country')
    
    return fig

app.run()```

Hey @Olivier_fr,

you have to switch the function parameters, the order is not corresponding to the order of the inputs.

import dash
from dash import Input, Output, html, dcc
import plotly.express as px

df = px.data.gapminder()
app = dash.Dash()

app.layout = html.Div([
    html.Div([dcc.Dropdown(options=df['continent'].unique(), value='Asia', id='select-continent'),

              dcc.Dropdown(options=df['country'].unique(), value='Afghanistan', id='select-country'),

              dcc.Graph(id='lifeexp-gdp')
              ]
             )
]
)


@app.callback(
    Output(component_id='lifeexp-gdp', component_property='figure'),
    [
        Input(component_id='select-country', component_property='value'),
        Input(component_id='select-continent', component_property='value')
    ]
)
def fn_sortie(selected_country, selected_continent):
    df_selected_continent = df[df['continent'] == selected_continent]
    df_selected_country = df_selected_continent[df_selected_continent['country'] == selected_country]

    fig = px.scatter(df_selected_country, x='gdpPercap', y='lifeExp',
                     size='pop', color='country', hover_name='country')

    return fig


if __name__ == "__main__":
    app.run(debug=True)

You might want to add a callback for populating the country drop-down depending on the continent drop-down in the future.

Many thanks, got it ! :ok_hand:

1 Like