# Dash: dropdown input to update bargraph out

**URL:** <https://community.plotly.com/t/dash-dropdown-input-to-update-bargraph-out/28604>\
**Category:** Dash Python\
**Created:** [September 12, 2019, 2:19pm UTC](https://community.plotly.com/t/dash-dropdown-input-to-update-bargraph-out/28604 "2019-09-12T14:19:41Z")\
**Posts on this page:** 11\
**Page:** 1

<div class="post-metadata">

**Author:** ![jhaseon](https://avatars.discourse-cdn.com/v4/letter/j/4da419/32.png) [@jhaseon](https://community.plotly.com/u/jhaseon)\
**Post date:** [September 12, 2019, 2:19pm UTC](https://community.plotly.com/t/dash-dropdown-input-to-update-bargraph-out/28604/1 "2019-09-12T14:19:41Z")

</div>

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](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?

---

<div class="post-metadata">

**Author:** ![flyingcujo](https://avatars.discourse-cdn.com/v4/letter/f/e480ec/32.png) [@flyingcujo](https://community.plotly.com/u/flyingcujo)\
**Post date:** [September 12, 2019, 3:26pm UTC](https://community.plotly.com/t/dash-dropdown-input-to-update-bargraph-out/28604/2 "2019-09-12T15:26:55Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![jhaseon](https://avatars.discourse-cdn.com/v4/letter/j/4da419/32.png) [@jhaseon](https://community.plotly.com/u/jhaseon)\
**Post date:** [September 12, 2019, 3:37pm UTC](https://community.plotly.com/t/dash-dropdown-input-to-update-bargraph-out/28604/3 "2019-09-12T15:37:44Z")

</div>

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

 ![dash](https://us1.discourse-cdn.com/flex024/uploads/plot/original/2X/d/d6655ecd3478a6a004db1acee31312f790e23153.png)

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

---

<div class="post-metadata">

**Author:** ![flyingcujo](https://avatars.discourse-cdn.com/v4/letter/f/e480ec/32.png) [@flyingcujo](https://community.plotly.com/u/flyingcujo)\
**Post date:** [September 12, 2019, 3:47pm UTC](https://community.plotly.com/t/dash-dropdown-input-to-update-bargraph-out/28604/4 "2019-09-12T15:47:49Z")

</div>

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](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.

---

<div class="post-metadata">

**Author:** ![jhaseon](https://avatars.discourse-cdn.com/v4/letter/j/4da419/32.png) [@jhaseon](https://community.plotly.com/u/jhaseon)\
**Post date:** [September 12, 2019, 5:24pm UTC](https://community.plotly.com/t/dash-dropdown-input-to-update-bargraph-out/28604/5 "2019-09-12T17:24:47Z")

</div>

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.

 ![dash%202](https://us1.discourse-cdn.com/flex024/uploads/plot/original/2X/a/afa067551d465c4171b3b4956916dda5c5b4d88d.png)

---

<div class="post-metadata">

**Author:** ![flyingcujo](https://avatars.discourse-cdn.com/v4/letter/f/e480ec/32.png) [@flyingcujo](https://community.plotly.com/u/flyingcujo)\
**Post date:** [September 12, 2019, 5:31pm UTC](https://community.plotly.com/t/dash-dropdown-input-to-update-bargraph-out/28604/6 "2019-09-12T17:31:11Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![jhaseon](https://avatars.discourse-cdn.com/v4/letter/j/4da419/32.png) [@jhaseon](https://community.plotly.com/u/jhaseon)\
**Post date:** [September 12, 2019, 5:34pm UTC](https://community.plotly.com/t/dash-dropdown-input-to-update-bargraph-out/28604/7 "2019-09-12T17:34:23Z")

</div>

> **[dash.csv](https://drive.google.com/file/d/1hJUjajusKLoI5rBoUtAG_eqffs-hOtkJ/view?usp=drive_open)**
>
> Google Drive file.

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

---

<div class="post-metadata">

**Author:** ![flyingcujo](https://avatars.discourse-cdn.com/v4/letter/f/e480ec/32.png) [@flyingcujo](https://community.plotly.com/u/flyingcujo)\
**Post date:** [September 12, 2019, 6:18pm UTC](https://community.plotly.com/t/dash-dropdown-input-to-update-bargraph-out/28604/8 "2019-09-12T18:18:07Z")

</div>

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

```python
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)
```

---

<div class="post-metadata">

**Author:** ![jhaseon](https://avatars.discourse-cdn.com/v4/letter/j/4da419/32.png) [@jhaseon](https://community.plotly.com/u/jhaseon)\
**Post date:** [September 12, 2019, 6:33pm UTC](https://community.plotly.com/t/dash-dropdown-input-to-update-bargraph-out/28604/9 "2019-09-12T18:33:17Z")

</div>

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() "

---

<div class="post-metadata">

**Author:** ![flyingcujo](https://avatars.discourse-cdn.com/v4/letter/f/e480ec/32.png) [@flyingcujo](https://community.plotly.com/u/flyingcujo)\
**Post date:** [September 12, 2019, 6:45pm UTC](https://community.plotly.com/t/dash-dropdown-input-to-update-bargraph-out/28604/10 "2019-09-12T18:45:44Z")

</div>

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:

```python
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/](https://dash-bootstrap-components.opensource.faculty.ai/) as they have components that are a little more polished and refined.

---

<div class="post-metadata">

**Author:** ![jhaseon](https://avatars.discourse-cdn.com/v4/letter/j/4da419/32.png) [@jhaseon](https://community.plotly.com/u/jhaseon)\
**Post date:** [September 12, 2019, 6:50pm UTC](https://community.plotly.com/t/dash-dropdown-input-to-update-bargraph-out/28604/11 "2019-09-12T18:50:05Z")

</div>

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!
