Help with simple bar chart with callback

Hello - Im having trouble with a very simple callback where I would like the months on the x axis and a count of each month for the y axis (and filtering by category in a dropdown)

I’m pretty new to dash/plotly so bare with me.

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

app.layout = html.Div([

 html.Div([
    dcc.Dropdown(
        id='category-dropdown',
        options=[{'label': i, 'value': i} for i in categories],
        value='cars',
    )
], className='four columns'),


### for some reason I need to add text after dropdown otherwise it is hidden
html.H3(
    children='Categories by Month',
    style={
        'textAlign': 'center',
    }
),

html.Div([
    dcc.Graph(id='category-graph'),
], className='row')
])


@app.callback(
    Output('category-graph', 'figure'),
    [Input('category-dropdown', 'value')])
 def update_graph(category_dropdown_name):
dff = df[df['category' == category_dropdown_name]]

return {
    'data': [dict(
        x=dff['months'].unique(),
        y=dff['months'],  # .value_counts().sort_index().reindex(months, fill_value=0),
       # i would like to get a count for each month (i tried to do a value count which seems to work on a 
         normal graph but not in a callback

   type='bar',
    )]
}


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

A histogram should do this for you. refer to this post on how to do it but if you need anything else explained don’t hesitate to ask! Welcome to the community by the way! Hope all goes well in your project!

Thanks for the quick reply! Still having some trouble and not sure if the callback is the reason. Is this what it should look like?

@app.callback(
        Output('category-graph', 'figure'),
        [Input('category-dropdown', 'value')])
def update_figure(category_dropdown_name):
    dff = df[df['category' == category_dropdown_name]]
    fig = go.Figure()
    fig.add_trace(go.Histogram(histfunc="count",  x=dff['month']))
    return fig

I would expect so. As long as there are repeating values in your list of months then that should create bins for each unique month and store how many times those months are in the list. Go ahead and share the result of that callback if its not to your liking maybe I can figure out whats wrong.

Side note: If not all the months in the calendar show up in the list, then those months wont be included. If you scroll down to ‘Custom Binning’ on this page. then you can see how to customize your bins!

I seem to be getting an error:

:stop_sign: Errors ( 1 )

:rescue_worker_helmet:Callback error updating category-graph.figure

Callback error updating category-graph.figure

KeyError: False

Traceback (most recent call last)

Could I see the full tracback please? I suspect it is stemming from this line:

dff = df[df['category' == category_dropdown_name]]

As a key error indicates that you are attempting to search a dictionary for a key that doesn’t exist in said dictionary. Also how is your data frame structured? That may have something to do with it too.

1 Like

I think you’re right because when I omit that line and ignore the callback, the graph shows just fine.

Traceback (most recent call last):
File “C:\FAST\Python\3.7.0\lib\site-packages\pandas\core\indexes\base.py”, line 2657, in get_loc
return self._engine.get_loc(key)
File “pandas_libs\index.pyx”, line 108, in pandas._libs.index.IndexEngine.get_loc

File “pandas_libs\index.pyx”, line 132, in pandas._libs.index.IndexEngine.get_loc

File “pandas_libs\hashtable_class_helper.pxi”, line 1601, in pandas._libs.hashtable.PyObjectHashTable.get_item

File “pandas_libs\hashtable_class_helper.pxi”, line 1608, in pandas._libs.hashtable.PyObjectHashTable.get_item

KeyError: False

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File “pandas_libs\hashtable_class_helper.pxi”, line 1608, in pandas._libs.hashtable.PyObjectHashTable.get_item

KeyError: False

Ok I figured it out, I had the bracket in the wrong place

dff = df[df[‘category’] == category_dropdown_name]

really appreciate your help!!

Hey no problem man! Happy coding!