Dash : Dynamically update an element based on radio option selected - python

I have a radio element and a text box element in my dash application. I'd like to update the text the field based on the selected option from a callback.
dbc.InputGroup(
[
dbc.RadioItems(
id="type",
persistence=True,
persistence_type="memory",
options=[
{"label": "option1", "value": "option1"},
{"label": "option2", "value": "option2"}
],
value="option1",
style={"margin-left":"8px"}
),
],
style={"margin-top":"20px","width": "80%", "float": "left"},
),
dbc.InputGroup(
[
dbc.InputGroupAddon("Floor", style={"margin-left":"8px"}),
dbc.Input(
id="floor",
persistence=True,
persistence_type="memory"
),
],
),
How do I make the text "Floor" to be dynamic based on the option selected in the radio?

You need to use the #app.callback in order to make your InputGroupAddon dynamic
import dash
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
app = dash.Dash(__name__)
app.layout = (
html.Div([
dbc.InputGroup([
dbc.RadioItems(
id="type",
persistence=True,
persistence_type="memory",
options=[
{"label": "option1", "value": "option1"},
{"label": "option2", "value": "option2"}
],
value="option1",
style={"margin-left":"8px"}
),
],
style={"margin-top":"20px","width": "80%", "float": "left"},
),
dbc.InputGroup([
dbc.InputGroupAddon(
id='dbc-input-addon',
style={"margin-left":"8px"}),
dbc.Input(
id="floor",
persistence=True,
persistence_type="memory"
),
])
])
)
#app.callback(
Output(component_id='dbc-input-addon', component_property='children'),
[Input(component_id='type', component_property='value')]
)
def change_input(option_value):
if option_value == 'option1':
input_txt = 'Floor'
elif option_value == 'option2':
input_txt = 'No floor'
return input_txt
if __name__ == '__main__':
app.run_server(debug=True)

Related

Why is Dash callback-function not triggered in python? (selected_columns)

I want to trigger an event if the checkbox of a dash-table is clicked. When I start the webapp, I see below output
* Serving Flask app 'app'
* Debug mode: on
aaaa
[]
aaaa
[]
where "aaaa" indicating the callback is triggered. But when I click the checkbox after the initial load, nothing happens. I would expect that if I click the checkbox of a table, the callback-function dummy was triggered. Why is it not triggered?
import dash
import dash_bootstrap_components as dbc
from dash import html
from dash import dcc, dash_table
import plotly.express as px
from dash.dependencies import Input, Output
import pandas as pd
# data source: https://www.kaggle.com/chubak/iranian-students-from-1968-to-2017
# data owner: Chubak Bidpaa
df = pd.read_csv('https://raw.githubusercontent.com/Coding-with-Adam/Dash-by-Plotly/master/Bootstrap/Side-Bar/iranian_students.csv')
app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
# styling the sidebar
SIDEBAR_STYLE = {
"position": "fixed",
"top": 0,
"left": 0,
"bottom": 0,
"width": "16rem",
"padding": "2rem 1rem",
"background-color": "#f8f9fa",
}
# padding for the page content
CONTENT_STYLE = {
"margin-left": "18rem",
"margin-right": "2rem",
"padding": "2rem 1rem",
}
sidebar = html.Div(
[
html.H2("", className="display-4"),
html.Hr(),
html.H2("Sidebar", className="display-4"),
html.Hr(),
html.P(
"Number of students per education level", className="lead"
),
dbc.Nav(
[
dbc.NavLink("Home", href="/", active="exact"),
dbc.NavLink("Page 1", href="/page-1", active="exact"),
dbc.NavLink("Page 2", href="/page-2", active="exact"),
],
vertical=True,
pills=True,
),
],
style=SIDEBAR_STYLE,
)
navbar = dbc.NavbarSimple(
children=[
dbc.NavItem(dbc.NavLink("Page 1", href="#")),
dbc.DropdownMenu(
children=[
dbc.DropdownMenuItem("More pages", header=True),
dbc.DropdownMenuItem("Page 2", href="#"),
dbc.DropdownMenuItem("Page 3", href="#"),
],
nav=True,
in_navbar=True,
label="More",
),
],
brand="NavbarSimple",
brand_href="#",
color="primary",
dark=True,
)
fig1 = px.bar(df, barmode='group', x='Years',
y=['Girls Kindergarten', 'Boys Kindergarten'])
fig1.update_layout(plot_bgcolor='rgb(10,10,10)')
children1 = [html.H1('Kindergarten in Iran',
style={'textAlign':'center'}),
dcc.Graph(id='bargraph',
figure=fig1),
dash_table.DataTable(
id='datatable-interactivity',
columns=[
{"name": i, "id": i, "deletable": True, "selectable": True} for i in df.columns
],
data=df.to_dict('records'),
editable=True,
filter_action="native",
sort_action="native",
sort_mode="multi",
column_selectable="single",
row_selectable="multi",
row_deletable=True,
selected_columns=[],
selected_rows=[],
page_action="native",
page_current= 0,
page_size= 10,
)]
content = html.Div(id="page-content", children=children1, style=CONTENT_STYLE)
app.layout = html.Div([
dcc.Location(id="url"),
sidebar,
navbar,
content
])
#fig1.update_layout(plot_bgcolor='rgb(10,10,10)')
"""
def update_styles(selected_columns):
return [{
'if': { 'column_id': i },
'background_color': '#D2F3FF'
} for i in selected_columns]
"""
#app.callback(
Output('datatable-interactivity', 'style_data_conditional'),
Input('datatable-interactivity', 'selected_columns')
)
def dummy(selected_columns):
print("aaaa")
print(selected_columns)
#app.callback(
Output("page-content", "children"),
[Input("url", "pathname")]
)
def render_page_content(pathname):
if pathname == "/":
return children1
elif pathname == "/page-1":
return children1
elif pathname == "/page-2":
return children1
# If the user tries to reach a different page, return a 404 message
return dbc.Jumbotron(
[
html.H1("404: Not found", className="text-danger"),
html.Hr(),
html.P(f"The pathname {pathname} was not recognised..."),
]
)
if __name__=='__main__':
app.run_server(debug=True)
The dummy function accepts a wrong input parameter. I have not worked with selected_columns, but selected_rows so far. A function input needed to be "chosen_rows" then for the selected_rows.

Chage a different vol with Dash_Slicer

I’m trying to change automatically the vol when someone choose the option from the dropdown, I have eje2.npz, eje3.npz, eje4.npz. This in order to have a different database and show different images with dashslider.
The dash_slider doesnt have an id as other ddc.
I am out of ideas.
import dash
import dash_html_components as html
import imageio
import dash_bootstrap_components as dbc
from dash_slicer import VolumeSlicer
from dash import Dash, dcc, html, Input, Output
app = dash.Dash(__name__, update_title=None)
vol = imageio.volread("eje1.npz")
slicer = VolumeSlicer(app, vol)
slicer.graph.config["scrollZoom"] = False
app.layout = dbc.Container([
dbc.Row([
html.H1("Reporte sobre postura", style={'text-align': 'center'}),
]),
dbc.Row([
dbc.Col([
dcc.Dropdown(id="slct_30",
options=[
{"label": "PRIMER", "value": 1},
{"label": "SEGUNDO", "value": 2},
{"label": "TERCERO", "value": 3},
{"label": "CUARTO", "value": 4}],
multi=False,
value=1,
style={'width': "80%"}
),
html.Div(id='output_container', children=[]),
html.Br(),
],width={'size':5, 'offset':5},),
]),
dbc.Row([
slicer.graph, slicer.slider, *slicer.stores
]),
])
#app.callback(
[Output(component_id='output_container',component_property='children')],
[Output(component_id='post_%', component_property='figure')],
[Input(component_id='slct_30', component_property='value')]
)
def update_graph(option_slctd):
print(option_slctd)
print(type(option_slctd))
container = "LAPSO DE 30 MINUTOS: {}".format(option_slctd)
return container
if __name__ == "__main__":
app.run_server(debug=True, dev_tools_props_check=False)
`

Sidebar with filters (dropdowns) in Plotly Dash

I am trying to program a sidebar with some filters but the callback update_output of this dropdown is not working (not throwing an error, just doing nothing).
I think it is because this dropdown is not in the main layout, because my layout is composed of the sidebar and a content. My dropdowns in this sidebar will be filters that will be applied to the dataframe that feeds the graphs of the dashboard and dashboard2 layouts.
My question is how or where should I program those callbacks to give functionality to my sidebar dropdowns?
sidebar = html.Div(
[
html.H2("Sidebar", className="display-4"),
html.Hr(),
html.P(
"Sidebar", className="lead"
),
dbc.Nav(
[
dbc.NavLink("Home", href="/", active="exact"),
dbc.NavLink("Page 1", href="/page-1", active="exact"),
dbc.NavLink("Page 2", href="/page-2", active="exact"),
],
vertical=True,
pills=True,
),
dcc.Dropdown(id='dropdown',value="City"),
html.Br(),
dcc.Dropdown(id='dropdown2',options=[])
],
style=SIDEBAR_STYLE,
)
content = html.Div(id="page-content", children=[], style=CONTENT_STYLE)
app.layout = html.Div([
dcc.Location(id="url"),
sidebar,
content
])
#app.callback(
Output('dropdown2', 'options'),
Input('dropdown', 'value')
)
def update_output(value):
return df[df["cities"].isin(value)]
#app.callback(
Output("page-content", "children"),
[Input("url", "pathname")]
)
def render_page_content(pathname):
if pathname == "/":
return dashboard.layout
elif pathname == "/page-1":
return dashboard.layout
elif pathname == "/page-2":
return dashboard2.layout
# return a 404 message when user tries to reach a different page
return dbc.Jumbotron(
[
html.H1("404: Not found", className="text-danger"),
html.Hr(),
html.P(f"The pathname {pathname} was not recognised..."),
]
)
if __name__=='__main__':
app.run_server(debug=True, port=8000)
I find checklists to be better for this purpose. If you're open to using that instead of dropdown menu to filter your dataframe, then the complete snippet below will produce the following Plotly Dash App.
Complete code:
from jupyter_dash import JupyterDash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State, ClientsideFunction
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import pandas as pd
import plotly.graph_objs as go
import numpy as np
import plotly.express as px
app = JupyterDash(external_stylesheets=[dbc.themes.SLATE])
df = px.data.stocks()
df = df.set_index('date')
controls = dbc.Card(
[
dbc.FormGroup(
[
dbc.Label("Checklist"),
dcc.Checklist(
id="column_select",
options=[{"label":col, "value": col} for col in df.columns],
value=[df.columns[0]],
labelStyle={'display': 'inline-block', 'width': '12em', 'line-height':'0.5em'}
),
],
),
],
body=True,
style = {'font-size': 'large'}
)
app.layout = dbc.Container(
[
html.H1("Dropdowns and checklists"),
html.Hr(),
dbc.Row([
dbc.Col([controls],xs = 4),
dbc.Col([
dbc.Row([
dbc.Col(dcc.Graph(id="graph"), style={'height': '420px'}),
])
]),
]),
],
fluid=True,
)
#app.callback(
Output("graph", "figure"),
[Input("column_select", "value"),],
)
def make_graph(cols):
fig = px.line(df, x = df.index, y = cols, template = 'plotly_dark')
return fig
app.run_server(mode='external', port = 8982)

Automatically select checkbox Python and Dash

I have this python code working - If a user selects the "Select All" checkbox, all the checkboxes are selected/unselected.
I need the code to automatically check/uncheck the "Select All" checkbox if all the checkboxes are checked/unchecked.
Thank you! I used Google Collab
!pip install jupyter-dash
import plotly.express as px
from jupyter_dash import JupyterDash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
from dash.dependencies import Input, Output, State
# Build App
app = JupyterDash(__name__)
app.layout = html.Div(
[
dcc.Checklist(
id="all-or-none",
options=[{"label": "Select All", "value": "All"}],
value=[],
labelStyle={"display": "inline-block"},
),
dcc.Checklist(
id="my-checklist",
options=[
{"label": "New York City", "value": "NYC"},
{"label": "Montréal", "value": "MTL"},
{"label": "San Francisco", "value": "SF"},
],
value=[],
labelStyle={"display": "inline-block"},
),
]
)
#app.callback(
Output("my-checklist", "value"),
[Input("all-or-none", "value")],
[State("my-checklist", "options")],
)
def select_all_none(all_selected, options):
all_or_none = []
all_or_none = [option["value"] for option in options if all_selected]
return all_or_none
# Run app and display result inline in the notebook
app.run_server(mode='inline')
One approach could be to put your my-checklist options inside a variable and pass this variable to the options property of my-checklist:
all_options=[
{"label": "New York City", "value": "NYC"},
{"label": "Montréal", "value": "MTL"},
{"label": "San Francisco", "value": "SF"},
]
Then you can check whether the number of selected options from my-checklist is equal to the length of all_options in your callback to determine if all options are selected.
Aditionally you need to check each time an option of my-checklist is selected in order to toggle the Select All checkbox.
For example:
#app.callback(
Output("my-checklist", "value"),
Output("all-or-none", "value"),
Input("all-or-none", "value"),
Input("my-checklist", "value"),
prevent_initial_call=True,
)
def select_all_none(all_selected, options):
ctx = dash.callback_context
triggerer_id = ctx.triggered[0]["prop_id"].split(".")[0]
my_checklist_options = []
all_or_none_options = []
if triggerer_id == "all-or-none":
if all_selected:
all_or_none_options = ["All"]
my_checklist_options = [option["value"] for option in all_options]
else:
if len(options) == len(all_options):
all_or_none_options = ["All"]
my_checklist_options = options
return my_checklist_options, all_or_none_options
I've dash.callback_context here to determine which Input triggered the callback. For more info on dash.callback_context see the documentation here.

How can user add their own values to a dash_core_components.Dropdown?

In my dropdown you should select from a list of workplaces but you should also be able to insert your own value.
How can I add a input field like "add value..." at the end of the list?
A basic version that implements Kay's suggestion of creating a callback that appends an option to the list of options. The following example uses a button click as Input and an input value as State:
from dash import Dash
import dash_html_components as html
import dash_core_components as dcc
from dash.dependencies import Output, Input, State
app = Dash(__name__)
app.layout = html.Div(
[
dcc.Dropdown(
id="dropdown",
options=[
{"label": "a", "value": "a"},
{"label": "b", "value": "b"},
{"label": "c", "value": "c"},
],
value="a",
),
dcc.Input(id="input", value="", placeholder="add value..."),
html.Button("Add Option", id="submit", n_clicks=0),
]
)
#app.callback(
Output("dropdown", "options"),
Input("submit", "n_clicks"),
State("input", "value"),
State("dropdown", "options"),
prevent_initial_call=True,
)
def add_dropdown_option(n_clicks, input_value, options):
return options + [{"label": input_value, "value": input_value}]
if __name__ == "__main__":
app.run_server()

Categories