Dash: dropdown input to update bargraph out

import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import plotly.graph_objs as go

external_stylesheets = [‘https://codepen.io/chriddyp/pen/bWLwgP.css’]

df = pd.read_csv(‘dash.csv’)
drug = df.groupby([‘drug’]).mean().round(2).reset_index()
dfToList = drug[‘drug’].tolist()

app = dash.Dash(name, external_stylesheets = external_stylesheets)

option_species = dict(zip(dfToList, dfToList))

app.layout = html.Div([
html.Div([

    html.Div([
        dcc.Dropdown(
            id = 'dropdown',
            options = [{"label": key, "value": value} for key, value in option_species.items()]),
dcc.Graph(id = 'indicator-graphic'),


            ])])])

@app.callback(
dash.dependencies.Output(‘indicator-graphic’, ‘figure’),
[dash.dependencies.Input(‘dropdown’, ‘value’)])
def update_graph(dropdown):
a = df.set_index([‘dropdown’])
name = ‘dropdown’
a1 = a.loc[[name]].mean().to_frame().reset_index()
return {
‘data’: [go.Bar(
x = a1[‘index’][:-1],
y = a1[0]
)]
}

In the following code, I am making a bargraph that would update and filter through a database based on a dropdown box.

I am getting the following errors

Callback error updating indicator-graphic.figure

and

KeyError: “None of [‘dropdown’] are in the columns”

Can anyone help me out on this?

I suspect the quotes around dropdown are the problem.

a = df.set_index([‘dropdown’])

Unless dropdown is a column name, the variable dropdown passed into your update_graph function is already a string containing the value selected.

a = df.set_index([dropdown]) should fix your error.

Thanks! If it’s not too much, I’m getting this error now

An empty graph is showing up but can’t get the data to flow through it

Do you get this error on page load? or after your select an option in your dropdown? If I had to guess I would say page-load. If so, it would appear that the dropdown parameter passed into it the function is None as no value has been set. Thus, you should add some error checking at the start of your callback.

For the error checking, check out the FAQ (https://dash.plot.ly/faqs) and look at the FAQ titled How do I determine which Input has changed? Utilize ctx = dash.callback_context in order to determine if your Inputs or States are populated. If not, you can return no_update (one required for each output parameter)…don’t forget to add the following to your list of imports…

from dash.dash import no_update

Also, you should try to avoid using global variables if you plan to deploy this app.

Thank you for your feedback.

So i added the following code

def update_graph(dropdown):
ctx = dash.callback_context

if not ctx.triggered:
    button_id = 'No clicks yet'
else:
    button_id = ctx.triggered[0]['prop_id'].split('.')[0]

ctx_msg = json.dumps({
    'states': ctx.states,
    'triggered': ctx.triggered,
    'inputs': ctx.inputs
}, indent=2)

The errors messages go away but still having a hard time figuring out how to get my bar graphs to populate.

I will definitely avoid global variables later, for now I wanted to just make a working model.

Can you provide the contents of the dash.csv file so I can run your code?

it’ a 4mb file that’s has about 465 rows and about 6 rows if i recall recorrectly.

I got it working. Here is the code with some modifications.

What did I do?

  1. Not sure if it’s necessary but I modified your app. statements - mainly to conform to how I wrote my app in order to eliminate this as a problem.
  2. Added a check for dropdown is None
  3. df.set_index requires an input to be a column name - not a value in the column as you programmed. I changed the input to 'drug'

Assumptions:

  1. You are running the latest version of Dash, etc
import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import plotly.graph_objs as go
from dash.dependencies import Input, Output, State
from dash.dash import no_update

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

df = pd.read_csv('dash.csv')
drug = df.groupby(['drug']).mean().round(2).reset_index()
dfToList = drug['drug'].tolist()

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
server = app.server
app.config.suppress_callback_exceptions = True
app.css.config.serve_locally = False

option_species = dict(zip(dfToList, dfToList))

app.layout = html.Div([
    html.Div([

        html.Div([
            dcc.Dropdown(
                id='dropdown',
                options=[{"label": key, "value": value} for key, value in option_species.items()]),
            dcc.Graph(id='indicator-graphic'),


        ])])])


@app.callback(
    output=Output('indicator-graphic', 'figure'),
    inputs=[Input('dropdown', 'value')])
def update_graph(dropdown):
  ctx = dash.callback_context
  # Check if triggered or dropdown value is None
  if not ctx.triggered or dropdown is None:
    return no_update

  # set_index requires an input that is a column name
  a = df.set_index(['drug'])
  name = dropdown
  a1 = a.loc[[name]].mean().to_frame().reset_index()
  return {'data': [go.Bar(
        x=a1['index'][:-1],
        y=a1[0]
        )]
        }

if __name__ == '__main__':
    app.run_server(debug=True)
1 Like

Thank you so much flyingcujo!!! I think the df.set_index was probably the main factor why the graphs didn’t show up and the check for the the dropdown being the reason why the app crashed on loadup!!!

I don’t know why but making this bar graph was harder than I thought. I read the documentation but still couldn’t figure it out!!

and the global variables you were talking about is this bit?

" a = df.set_index([‘drug’])
name = dropdown
a1 = a.loc[[name]].mean().to_frame().reset_index() "

You’re welcome. Glad to help.

For me, I suffered just like you…looked at lots of example and hit the forum.

The global variables are:

df = pd.read_csv('dash.csv')
drug = df.groupby(['drug']).mean().round(2).reset_index()
dfToList = drug['drug'].tolist()
option_species = dict(zip(dfToList, dfToList))

Look into the dcc.Store component which allows you to store json-friendly variables.

Good luck in your app development! You may also like https://dash-bootstrap-components.opensource.faculty.ai/ as they have components that are a little more polished and refined.

Thanks and good luck to you as well!

I will definitely be looking at those components.

If you ever need anything from me as well, contact me!! I owe you a big one!

1 Like