Coding-with-Adam / Dash-by-Plotly

Interactive data analytics
dash-by-plotly.coding-with-adam.vercel.app
1.47k stars 1.69k forks source link

Dash Callback function not responding; Error: Duplicate Callback Output #3

Closed SambitD23 closed 3 years ago

SambitD23 commented 3 years ago

I am trying to create a dashboard consisting of 8 buttons, each of which corresponds to a filtered df and 4 dropdowns. The attempt was to take the filtered df according to the triggered button and use 4 columns of the df for 'options' of 4 different dcc.dropdown. But dash shows this error message:

In the callback for output(s): MBD.options Urbanity.options Outlet.options Chain.options Output 1 (Urbanity.options) is already in use. Any given output can only have one callback that sets it. To resolve this situation, try combining these into one callback function, distinguishing the trigger by using dash.callback_context if necessary.

My callback is:

@app.callback([Output('MBD', 'options'), Output('Urbanity', 'options'), Output('Outlet', 'options'),
           Output('Chain', 'options')],
           [Input('all','id'), Input('fmcg','id'), Input('bev','id'), Input('tob','id'),
           Input('food','id'), Input('drug','id'), Input('liquor','id'), 
           Input('unilever','id')])
def update_dd(all_b, fmcg_b, bev_b, tob_b, food_b, drug_b, liq_b, unil_b):
    ctx = dash.callback_context
    dff = pd.DataFrame()

if not ctx.triggered:
    button_id  = 'all.id'
else:
    button_id = ctx.triggered[0]['prop_id']
if button_id == 'all.id' :
    dff = alloutlet_df.copy()
elif button_id == 'fmcg.id':
    dff = fmcg_df.copy()
elif button_id == 'bev.id':
    dff = bev_df.copy()
elif button_id == 'tob.id':
    dff = tob_df.copy()
elif button_id == 'food.id':
    dff = food_df.copy()
elif button_id == 'drug.id':
    dff = drug_df.copy()
elif button_id == 'liquor.id':
    dff = liquor_df.copy()
elif button_id == 'unilever.id':
    dff = unilever_df.copy()
else:
    dff = df.copy()

mbd_opt = {'label':dff['Region'].unique(), 'value':dff['Region'].unique()} 
urb_opt = {'label':dff['Urbanity'].unique(), 'value': dff['Urbanity'].unique()} 
out_opt = {'label':dff['Outype_panel'].unique(), 'value':dff['Outype_panel'].unique()} 
chain_opt = {'label':dff['CHAIN'].unique(), 'value':dff['CHAIN'].unique()} 
return [mbd_opt, urb_opt, out_opt, chain_opt]
Coding-with-Adam commented 3 years ago

Hi @SambitD23 , Yes, that's a well-known error. Did you get it fixed by using the Urbanity.options only once?

SambitD23 commented 3 years ago

No. I'm stuck. I tried a lot to bypass it but this error keeps on coming. Can you help?

Coding-with-Adam commented 3 years ago

This error should not come up unless you have Output('Urbanity', 'options') in two different callback decorators. Do you use it again somewhere else?

SambitD23 commented 3 years ago

No I just have one callback and still it is giving the error. I am pasting the entire code below. Couldn't figure it out yet :(

app = dash.Dash(__name__, external_stylesheets=[dbc.themes.DARKLY])

app.layout = html.Div([
        dbc.Row([dbc.Col(html.H1("NUE Summary", style = {'margin-top':'20px', 'margin-bottom':'30px', 'margin-left':'40px'}),
                        width = {'size': 2},
                        ),
                dbc.Col([dbc.Button("All Outlet Types",id = "all", color="primary", className="mr-1",size="lg", 
                                    disabled = (Disabled== "True"), style = {'margin-top':'20px', 
                                                                             'margin-bottom':'30px','float':'right'}),
                         dbc.Button("Unilever",id = "unilever", color="primary",size= "lg", className="mr-1",
                                    disabled = (Disabled== "True"),
                                    style = {'margin-top':'20px', 'margin-bottom':'30px', 'float':'right'}),
                         dbc.Button("Liquor", id = "liquor", color="primary",size= "lg", className="mr-1",
                                    disabled = (Disabled== "True"),
                                    style = {'margin-top':'20px', 'margin-bottom':'30px', 'float':'right'}),
                         dbc.Button("Drug",id = "drug", color="primary",size= "lg", className="mr-1",
                                    disabled = (Disabled== "True"),
                                    style = {'margin-top':'20px', 'margin-bottom':'30px', 'float':'right'}),
                         dbc.Button("Food",id = "food", color="primary",size= "lg", className="mr-1",
                                    disabled = (Disabled== "True"),
                                    style = {'margin-top':'20px', 'margin-bottom':'30px', 'float':'right'}),
                         dbc.Button("Tobacco",id = "tob", color="primary",size= "lg", className="mr-1",
                                    disabled = (Disabled== "True"),
                                    style = {'margin-top':'20px', 'margin-bottom':'30px', 'float':'right'}),
                         dbc.Button("Beverage",id = "bev", color="primary",size= "lg", className="mr-1",
                                    disabled = (Disabled== "True"),
                                    style = {'margin-top':'20px', 'margin-bottom':'30px', 'float':'right'}),
                         dbc.Button("FMCG",id = "fmcg", color="primary",size= "lg", className="mr-1", 
                                    disabled = (Disabled== "True"),
                                    style = {'margin-top':'20px', 'margin-bottom':'30px', 'float':'right'})
                         ], width = 10)
                ]),
        dbc.Row([dbc.Col([html.H4("Please select granularities",
                                  style = {'text-align':'center','margin-top':'20px', 'margin-bottom':'30px'}),
                          dcc.Dropdown(id= 'MBD', multi=True, options = [{'label':i, 'value':i} for i in df.Region.unique()], 
                                       style = {'text-align':'left', 'margin-top':'20px', 'margin-bottom':'20px', 
                                                'margin-left':'10px','color':'#212121'}, placeholder = "Standard MBDs"),

                          dcc.Dropdown(id= 'Urbanity', multi=True,  options = [{'label':j, 'value':j} for j in df.Urbanity.unique()],
                                       style = {'text-align':'left',
                                       'margin-top':'20px', 'margin-bottom':'20px',
                                       'margin-left':'10px', 'color':'#222121'},placeholder = "Urban/Rural"),

                          dcc.Dropdown(id= 'Outlet', multi=True,  options = [{'label':k, 'value':k} for k in df.Outype_panel.unique()], 
                                       style = {'text-align':'left','margin-top':'20px', 'margin-bottom':'20px',
                                                'margin-left':'10px', 'color':'#222121'}, placeholder = "Shop Types"),

                          dcc.Dropdown(id= 'Chain', multi=True, options = [{'label':l, 'value':l} for l in df.CHAIN.unique()], 
                                       style = {'text-align':'left','margin-top':'20px', 
                                                'margin-bottom':'20px', 'margin-left':'10px', 'color':'#222121'}, placeholder = "Chain/Non-Chain")],
                                       width = 2),
                dbc.Col(dcc.Graph(id = 'Trend', style= {'height': "75vh"}),width =5),
                dbc.Col(dbc.Table.from_dataframe( df=pd.DataFrame() , id= 'table',  style= {'height': "30%"}, size = 'sm', 
                                                 striped = True), width=5),
                ]),
        dbc.Row(html.H6("")),
        dbc.Row([
                dbc.Col([
                        html.H4("Select Chart Type", style = {'text-align':'left','margin-top':'20px', 
                                                              'margin-bottom':'30px','margin-left':'40px'}),

                        dbc.Button("Absolute Difference",id = 'abs', color = "info", className = "mr-1", size = "lg", active=True,
                                    style = {'margin-left':'40px', 'margin-top':'20px', 'margin-bottom':'20px'}),

                        dbc.Button("Relative Difference", id = 'rel', color = "info", className = "mr-1", size = "lg",
                                    style = {'margin-left':'40px', 'margin-top':'20px', 'margin-bottom':'20px'})
                        ], width = 2),
                dbc.Col(dcc.Graph(id = 'cba'),width ={'size':4}),
                dbc.Col(dcc.Graph(id = 'contri'),width =5),
                dbc.Col(html.Div(style={"background-color": "#424242"}),style={"background-color": "#424242"}, width = 2)
                ])
        ])

@app.callback([Output('MBD', 'options'), Output('Urbanity', 'options'), Output('Outlet', 'options'),
               Output('Chain', 'options')],
              [Input('all','id'), Input('fmcg','id'), Input('bev','id'), Input('tob','id'),
               Input('food','id'), Input('drug','id'), Input('liquor','id'), 
               Input('unilever','id')])
def update_dd(all_b, fmcg_b, bev_b, tob_b, food_b, drug_b, liq_b, unil_b):
    ctx = dash.callback_context
    dff = pd.DataFrame()

    if not ctx.triggered:
        button_id  = 'all.id'
    else:
        button_id = ctx.triggered[0]['prop_id']
    if button_id == 'all.id' :
        dff = alloutlet_df.copy()
    elif button_id == 'fmcg.id':
        dff = fmcg_df.copy()
    elif button_id == 'bev.id':
        dff = bev_df.copy()
    elif button_id == 'tob.id':
        dff = tob_df.copy()
    elif button_id == 'food.id':
        dff = food_df.copy()
    elif button_id == 'drug.id':
        dff = drug_df.copy()
    elif button_id == 'liquor.id':
        dff = liquor_df.copy()
    elif button_id == 'unilever.id':
        dff = unilever_df.copy()
    else:
        dff = df.copy()

    mbd_opt = [{'label': mbd, 'value': mbd} for mbd in dff['Region'].unique()]

    urb_opt = [{'label': urb, 'value': urb} for urb in dff['Urbanity'].unique()] 

    out_opt = [{'label': out, 'value': out} for out in dff['Outype_panel'].unique()]

    chain_opt = [{'label': ch, 'value': ch} for ch in dff['CHAIN'].unique()]
    return {'options': mbd_opt}
    return {'options': urb_opt}
    return {'options': out_opt}
    return {'options': chain_opt}

if( __name__ == "__main__"):
    app.run_server(debug=True, use_reloader=False)
Coding-with-Adam commented 3 years ago

Try to change your function returns. You can't return four times. You have to return four objects in one return, like this: return {'options': mbd_opt}, {'options': urb_opt}, {'options': out_opt}, {'options': chain_opt}

Let me know if that works.

SambitD23 commented 3 years ago

No, now it's returning the following error. It's stuck between either the previous error or the following:

Invalid argument `options` passed into Dropdown with ID "Chain".
Expected an array.
Was supplied type `object`.
Value provided: 
{
  "options": [
    {
      "label": "0",
      "value": "0"
    },
    {
      "label": "1",
      "value": "1"
    },
    {
      "label": "NC",
      "value": "NC"
    }
  ]
}

The same error is shown for the other three dropdowns as well.

Coding-with-Adam commented 3 years ago

Sorry. my bad. You don't have to return the whole {options: mbd_opt}, becuase the options value is already part of the callbakc output. It should work if you just return this:

return mbd_opt, urb_opt, out_opt, chain_opt