jeudi 22 avril 2021

To select all other checkboxes when checked the option (all) is clicked in dash

I need a logic which selects all checkboxes when the option All is checked in the checklist And the graph would change accordingly.

Or if we can disable the other checkboxes(x,y,x and x1, x2,x3) if the option All is Checked.

The code which I have used is as follows

import pandas as pd
import plotly.graph_objs as go
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
df = pd.DataFrame({'category' : ['A','A','A','B','B','B'],
               'subcategory' : ['l', 'y', 'z', 'x1','y1','z1'],
               'x_coord' : [1, 2,3,2,2,2],
               'y_coord' : [1,3,2,1,3,2]})
# lists of categories
options1 = sorted(df["category"].unique().tolist())
# dictionary of category - subcategories
all_options = df.groupby("category")["subcategory"].unique()\
            .apply(list).to_dict()
# we add as first subcategory for each category `all`
for k, v in all_options.items():
    all_options[k].insert(0, 'all')
app = dash.Dash()
app.layout = html.Div([
dcc.Dropdown(
    id='first-dropdown',
    options=[{'label': k, 'value': k} for k in all_options.keys()],
    value=options1[0]
),

html.Hr(),

dcc.Dropdown(id='second-dropdown'),

html.Hr(),

dcc.Graph(id='display-selected-values')
])
# the following two callbacks generate a dynamic 2 option
@app.callback(
    dash.dependencies.Output('second-dropdown', 'options'),
    [dash.dependencies.Input('first-dropdown', 'value')])
def set_2_options(first_option):
   return [{'label': i, 'value': i} for i in all_options[first_option]]


@app.callback(
dash.dependencies.Output('second-dropdown', 'value'),
[dash.dependencies.Input('second-dropdown', 'options')])
def set_2_value(available_options):
   return available_options[0]['value']
@app.callback(
   dash.dependencies.Output('display-selected-values', 'figure'),
   [dash.dependencies.Input('first-dropdown', 'value'),
   dash.dependencies.Input('second-dropdown', 'value')])
def update_graph(selected_first, selected_second):
    if selected_second == 'all':
       ddf = df[df["category"]==selected_first]
    else:
        ddf = df[(df["category"]==selected_first) &
             (df["subcategory"]==selected_second)]

fig = go.Figure()
fig.add_trace(
    go.Scatter(x=ddf["x_coord"],
               y=ddf["y_coord"],
               marker = dict(size=15, color='green'),
               mode='markers'))
return fig

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

If the All option is checked from the checkbox for category A then the subcategories can either be all selected(i.e checked) or the can be disbled and the graph must be shown for all the subcategories.

What calls and function is necessary to achieve these. Thanks in Advance!!!




Aucun commentaire:

Enregistrer un commentaire