Black Lives Matter. Please consider donating to Black Girls Code today.

Table_experiment & Graph Help

I am playing with table experiments. My table contains simple statistics by county. I want to select a row (which represents data for one county) and then have a graph below chart a bar for the row that was selected. It’s almost there, but when selecting more than one row, I get multiple bars for a single county (see below screen shot). I want there to be just one bar for each county in the graph.

Something must be wrong in my callback function, but I’m not sure what it is. Hoping for some help from you wizards out there. Code below:

app = dash.Dash()

df = pd.read_csv(‘Table_Test.csv’)

app.layout = html.Div([
html.Label(‘This is a sample table’),
dt.DataTable(
rows = df.to_dict(‘records’),
row_selectable = True,
filterable = True,
sortable = True,
editable = False,
selected_row_indices = [],
id = ‘table1’
),
html.Br(),
dcc.Graph(
id = ‘graph-gapminder’)
],className = ‘container’)

@app.callback(
Output(‘graph-gapminder’, ‘figure’),
[Input(‘table1’, ‘rows’),
Input(‘table1’, ‘selected_row_indices’)])
def update_figure(rows, selected_row_indices):

traces =[]
for County in selected_row_indices:
    df_selected_rows = df.loc[selected_row_indices]
    traces.append(go.Bar(
            x = df_selected_rows['County'],
            y = df_selected_rows['Avg_100ADP'],
        ))
return {'data': traces,
        'layout':go.Layout(title = 'Avg Inpatient Days',
                            xaxis = dict(title='County'),
                            yaxis = dict(title='Hospital Days'))}

app.css.append_css({
‘external_url’: ‘https://codepen.io/chriddyp/pen/bWLwgP.css
})

if name == ‘main’:
app.run_server(debug=True)

Thank you for any help!

I have revised the callback. It is not necessary to do the for loop so I removed it.
Hope it helps.

@app.callback(
Output('graph-gapminder', 'figure'),
[Input('table1', 'rows'),
Input('table1', 'selected_row_indices')])
def update_figure(rows, selected_row_indices):
    df_selected_rows = df.loc[selected_row_indices]
    traces=[go.Bar(
                x = df_selected_rows['County'],
                y = df_selected_rows['Avg_100ADP'],
            )]
    return {'data': traces,
            'layout':go.Layout(title = 'Avg Inpatient Days',
                                xaxis = dict(title='County'),
                                yaxis = dict(title='Hospital Days'))}

You rock jo_py! That was the fix. Thank you for taking the time, I really appreciate it.