So, I have this very simplified Dash app example. Code is below:
import pandas as pd import dash import dash_html_components as html import dash_core_components as dcc import plotly.express as px from dash.dependencies import Input, Output data = {'Fruits': ['apple', 'orange', 'banana'], 'Number': [10, 15, 7]} df = pd.DataFrame(data, columns=['Fruits', 'Number']) fruits_options = df['Fruits'] app = dash.Dash(__name__) app.layout = html.Div(children=[ html.H1(children='Fruits Bar Chart'), html.Div([ dcc.Dropdown( id='dropdown', options=[{'label': i, 'value': i} for i in fruits_options], value='All Fruits', multi=True ), html.Div(dcc.Graph(id='graph')), ]), ]) @app.callback( Output(component_id='graph', component_property='figure'), Input(component_id='dropdown', component_property='value') ) def update_graph(fruits): if 'All Fruits' in fruits: dff = df.copy() else: dff = df[df['Fruits'].isin(fruits)] figure = px.bar(dff, x=dff['Fruits'], y=dff['Number']) return figure if __name__ == '__main__': app.run_server(debug=True)
User can select multiple options and they will appear on the chart but when the user chose to clear all
(x on the right side) it shows this error:
ValueError: Cannot accept list of column references or list of columns for both `x` and `y`.
Does anyone have a suggestion on how to fix this? Also, If possible I would like to return to the initial state of the chart when clear all is selected.
Thanks in advance.
Advertisement
Answer
The remove the error, you need to handle the case where fruits
is an empty list. It could be as simple as replacing the
'All Fruits' in fruits
condition by
not fruits or 'All Fruits' in fruits
Since not fruits
evaluates to True
when the fruits
variable is an empty list and your initial state was 'All Fruits'
, this simple change should yield the desired outcome.