I have a dropdown based on the column ItemCategory. If no ItemCategory is selected, the scatter plot and dash table will show all data. If an ItemCategory is selected, the scatter plot and dash table will update to only show the data for the selected ItemCategory. Here is the code that works for this part.
report=pd.read_excel('Report.xlsx')
app=Dash(__name__)
app.layout=html.Div([dcc.Dropdown(options=[{'label':x,'value':x} for x in report['ItemCategory'].unique()],
placeholder='Select an Item Category',
id='dynamic-dropdown'),
dcc.Graph(id='dynamic-graph'),
dash_table.DataTable(data=report.to_dict('records'),
columns=[{'name':y,'id':y} for y in report.columns],
page_size=10,
id='dynamic-table')])
@app.callback([Output('dynamic-graph','figure'),
Output('dynamic-table','data')],
[Input('dynamic-dropdown','value')])
def dropdown_update(dropdown_value):
if dropdown_value is None:
fig1=px.scatter(report,x='Amount',y='Quantity',color='Classification')
return fig1,report.to_dict('records')
else:
df_category=report[report['ItemCategory'].isin([dropdown_value])]
fig2=px.scatter(df_category,x='Amount',y='Quantity',color='Classification')
return fig2,df_category.to_dict('records')
if __name__=='__main__':
app.run_server(debug=False)
I also want to update the dash table to match the points displayed on the scatter plot when users zoom in on particular sections of the chart, select particular categories in the legend etc. Based on this example (Dash: How to select data points either in the table which updates the plot and on the graph which updates the selection on the table?), this is the code I placed after my dropdown_update function but I cannot seem to get it to work.
@app.callback(Output('dynamic-table','selected_rows'),
[Input('dynamic-graph','selectedData')])
def graph_update_table(selectedData):
selected_term_list,selected_rows=[],[]
if selectedData is not None:
for point in selectedData['points']:
selected_term_list.append(point['customdata'][0])
selected_rows=report[report['Item'].isin(selected_term_list)].index.tolist() # Item is the second column in my data
return selected_rows
return selected_rows
I also tried referencing to this example (Plotly Dash: filter DataTable based on plot selection) and it's not working too.
@app.callback(Output('dynamic-table','data'),
[Input('dynamic-graph','clickData')])
def on_trace_click(click_data):
p = trace_click['points'][0]
if 'customdata' in p:
key = p['customdata']['my-key']
df_f = get_corresponding_rows(me_report, key)
return df_f.to_dict('records')
def get_corresponding_rows(me_report, my_key):
return me_report[me_report['Item'] == my_key] # Item is the second column in my data
Not sure what I'm doing wrong. Help please. Thank you!