nonamednono
nonamednono

Reputation: 49

Dash callback with dropdown

I'm trying to figure out how to implement a dropdown for a plot with multiple countries. I'm pretty new with dash and plotly. This is my code:

import pandas as pd
import plotly.express as px
import dash
import dash_core_components as dcc
import dash_html_components as html

df = pd.read_csv('https://api.statbank.dk/v1/data/mpk100/CSV?valuePresentation=Value&timeOrder=Ascending&LAND=*&Tid=*', sep=';')
df = df[df['INDHOLD'] != '..']
df['rate'] = df['INDHOLD'].str.replace(',', '.').astype(float)
available_countries = df['LAND'].unique()
df.groupby('LAND')

app = dash.Dash()
app.layout = html.Div([
    dcc.Graph(
        id='mpk100'
    ),
dcc.Dropdown(
                  id = "dropdown_mpk100",
                  options=[{'label': i, 'value': i} for i in available_countries],
                  value=['DANMARK', 'USA'], #Initial values,
                  multi=True)
    

@app.callback(Output(component_id='fig-mpk100',component_property='figure'),
    [Input(component_id='dropdown_mpk100', component_property='value')])

 def update_df('value'):
return dep_var

    
app.run_server(debug=True, use_reloader=False)  # Turn off reloader if inside Jupyter

With this code neither a dropdown with the available countries or a graph shows up in dash. Can someone explain how to deal with this and probably give a solution?

Upvotes: 1

Views: 10503

Answers (1)

rpanai
rpanai

Reputation: 13437

There are several missing part in your code. In particular you are not generating any figure. Here I'm basically filtering df for all the countries you want to plot and then plot all of them as lines with plotly.express. You can eventually add traces with plotly.graph_objs if you prefer to do so.

import pandas as pd
import plotly.express as px
import dash
import dash_core_components as dcc
import dash_html_components as html

df = pd.read_csv('https://api.statbank.dk/v1/data/mpk100/CSV?valuePresentation=Value&timeOrder=Ascending&LAND=*&Tid=*', sep=';')
df = df[df['INDHOLD'] != '..']
df['rate'] = df['INDHOLD'].str.replace(',', '.').astype(float)
available_countries = df['LAND'].unique()

app = dash.Dash()
app.layout = html.Div([
    dcc.Dropdown(
        id='demo-dropdown',
        options=[{'label': k, 'value': k} for k in available_countries],
        value=['Danmark', 'USA'],
        multi=True
    ),

    html.Hr(),
    dcc.Graph(id='display-selected-values'),

])

@app.callback(
    dash.dependencies.Output('display-selected-values', 'figure'),
    [dash.dependencies.Input('demo-dropdown', 'value')])
def update_output(value):
    ts = df[df["LAND"].isin(value)]
    fig = px.line(ts, x="TID", y="rate", color="LAND")
    return fig


if __name__ == '__main__':
    app.run_server()

Upvotes: 1

Related Questions