1
votes

hope you are well!. I'm quite new to Python, dash & Plotly and i am struggling to understand why i am unable to sync the dropdown bar with the graph its connected to.

when Multi is at default the graph web page works fine however when i change the option its stops working.

if you are able to correct the code and provide some narrative to why my code doesnt work that would be much appreciated.

some narratives: in the excel sheet im uploading there is info on all states however i am only interested in 5 states in this example hence the dictionary containing 5 states

dff = dff[dff["state"] == option_selected]

the variable state here exists in the excel sheet thats in being imported into the data frame.

also i am using this data set from covidtracking.com

thank you in advance!

import pandas as pd
import plotly.express as px  
import plotly.graph_objects as go
from dash import Dash, dcc, html, Input, Output  


app = Dash(__name__)

# -- Import and clean data (importing csv into pandas)

df = pd.read_csv("all-states-history.csv")

# ------------------------------------------------------------------------------
# App layout
app.layout = html.Div([

    html.H1("CV deaths by state", style={'text-align': 'center'}),

    dcc.Dropdown(id="slct_year",
                 options=[
                      {'label':'AZ','value': 'AZ'},
                      {'label':'CA','value': 'CA'},
                      {'label':'NY','value': 'NY'},
                      {'label':'FL','value': 'FL'},
                      {'label':'MA','value': 'MA'}],
                 multi=True,
                 #value=2015,
                 style={'width': "40%"}
                 ),

    html.Div(id='output_container', children=[]),
    html.Br(),

    dcc.Graph(id='my_map', figure={})

])


# ------------------------------------------------------------------------------
# Connect the Plotly graphs with Dash Components
@app.callback(
    [Output(component_id='output_container', component_property='children'),
     Output(component_id='my_map', component_property='figure')],
    [Input(component_id='slct_year', component_property='value')]
)
def update_graph(option_selected):
    print(option_selected)
    print(type(option_selected))

    container = "The state chosen by user was: {}".format(option_selected)

    dff = df.copy()
    dff = dff[dff["state"] == option_selected]


    # Plotly Express
    fig = px.choropleth(
        data_frame=dff,
        locationmode='USA-states',
        locations='state',
        scope="usa",
        color='state',
        hover_data=['state'],
        color_continuous_scale=px.colors.sequential.YlOrRd,
        
        template='plotly_dark'
    )


    return (container, fig)


# ------------------------------------------------------------------------------
if __name__ == '__main__':
    # For Development only, otherwise use gunicorn or uwsgi to launch, e.g.
    # gunicorn -b 0.0.0.0:8050 index:app.server
    app.run_server(
        port=8050,
        host='0.0.0.0'
    )
1
i added a link to all-states-history.csv so that your code is reproducible - Derek O

1 Answers

0
votes

There are two issues I can see you'll run into: the first is that once the user selects from the dropdown, option_selected will be of type 'list' and the syntax for slicing a DataFrame based on whether an element is in a list is to use .isin.

The other issue is that when the dash app is initialized option_selected will be NoneType because the user hasn't yet selected from the dropdown menu. You can include a condition to check for that:

if option_selected is not None:
    dff = dff[dff["state"].isin(option_selected)]

Then the dash app runs and you can select the 5 states.

enter image description here