I’m just getting to grips with Dash but am coming across a problem I can’t resolve. I am trying to pass a default dropdown value to a line chart upon page load, but even though the value is present in the dropdown menu it doesn’t render in the chart:
As soon as I select another country (region) though, the chart works as expected:
How do I get the chart to load with my default dropdown value (England)? Here’s the code:
JavaScript
x
23
23
1
df_prices = pd.read_csv('Average-prices-2022-01.csv')
2
df_prices["Date"] = pd.to_datetime(df_prices["Date"])
3
4
app = JupyterDash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
5
6
app.layout = html.Div(children=[html.H1('My Dash App'), html.Br(),
7
html.Div(children=[html.H3('Select Country'), dcc.Dropdown(id='region_picker', options=[{"label":region, "value": region} for region in df_prices["Region_Name"].unique()], value='England' ,multi=True, clearable=True, style={'text-align':'left'})], style={'display':'inline-block', 'vertical-align':'top', 'width':'25%', 'padding-right': '5px'}),
8
html.Div(children=[html.H3("House Prices", style={'padding-left':'30px'}), dcc.Graph(id="price_chart")], style={'display':'inline-block', 'width':'75%'})], style={'margin': '50px'})
9
10
@app.callback(
11
Output(component_id="price_chart", component_property="figure"),
12
Input(component_id="region_picker", component_property="value")
13
)
14
15
16
def update_region(input_country):
17
#input_country = 'England'
18
data = df_prices.copy(deep=True)
19
data = data[data['Region_Name'].isin(list(input_country))]
20
21
line_chart = px.line(data_frame = data, x="Date", y="Average_Price", title=f'Average House Price in {input_country}',color='Region_Name', render_mode="webgl")
22
return line_chart
23
Thanks!
Advertisement
Answer
The ‘value’ attribute of the dropdown component has to be a list instead of string while setting multi as True. Just wrap the square brackets around the value as follows and you should be good to go:
JavaScript
1
2
1
dcc.Dropdown(id='region_picker', options=[{"label":region, "value": region} for region in df_prices["Region_Name"].unique()], value=['England'] ,multi=True, clearable=True, style={'text-align':'left'})
2