✊🏿 Black Lives Matter. Please consider donating to Black Girls Code today.
⚾️ It's finally Baseball season! Root for the home team... & Register for our Sports Analytics Webinar!

Problem doing basic callback -> Filter calculation+graph by year with slider

I am trying to build an interactive graph with a slider. The value of the slider (the year) filters the data which is displayed on the graph. So if I set the year to 2018 in the slider, it does the value_counts() calculation and graphs only the data for which the year column = 2018. All pretty basic stuff.

My code is as follows:

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']

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

#df = pd.read_csv('/home/xxxxx/Desktop/Sentences.csv', low_memory=False)
df = pd.read_csv('/Users/xxxxx/2018 Work/Data/Sentences.csv', low_memory=False)
df = df[['case_type', 'disposal_ho_group_desc_msd', 'dea_snapshot_date', 'prison_days_name', 'year']]

app.layout = html.Div(children=[
    html.H1(children='Hello Dash'),

    html.Div(children='''
        Dash: A web application framework for Python.
    '''),

    dcc.Graph(
        id='example_graph_4',
        figure={
            'data': [
		{'x': ((df['prison_days_name'].value_counts().index.tolist())[:5]), 
         'y':(df['prison_days_name'].value_counts()[:5]) , 
         'type': 'bar', 'name': 'length of time period'},
            ],
            'layout': {
                'title': 'CCC outcome by length'
            }
        }
    ),

	html.Label('Slider'),
   		dcc.Slider(
        	id='year_slider',
        	min=df['year'].min(),
        	max=df['year'].max(),
        	value=df['year'].max(),
        	marks={str(year): str(year) for year in df['year'].unique()}
	),

])

@app.callback(
Output('example_graph_4', 'figure'),
[Input('year_slider', 'value')]
)

def update_graph(value):
      return {'data': [
        {'x': df[df['year']==v]((df['prison_days_name'].value_counts().index.tolist())[:5]),
        'y': df[df['year']==v](df['prison_days_name'].value_counts()[:5]), 
        'type': 'bar', 'name': 'length of time period'}
     for v in value]
}


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

But it doesn’t work, I get the error message:

Traceback (most recent call last):
File "app.py", line 93, in <module>
Output('example_graph_4', 'figure'),
NameError: name 'Output' is not defined

Would someone be able to explain why this isn’t working? It looks to me as if output is clearly defined both by the id and by the subsection of the id.

You haven’t imported Input and Output. Add the following to your imports

from dash.dependencies import Input, Output
1 Like

Yeah you are right! I must have missed that one, thanks