Below is my code, but the code not works,
first 5 options in dropdown returns a graph and
option 6 needs to display a google form
without the 6th option the code is working fine, but the 6th option for displaying gform is throwing errror in dash
help me solve this
app.layout=html.Div(children=[dcc.Dropdown(
id='FirstDropdown',
options=[
{'label':"graph1",'value':'v1'},
{'label':"graph2",'value':'v2'},
{'label':"graph3,'value':'v3'},
{'label':"graph4",'value':'v4'},
{'label':"graph 5",'value':'v5'},
{'label':"g-form",'value':'v6'}
],
placeholder="Please choose an option",
value='v1'
),
html.Div(dcc.Graph(id='graph'))
])
#app.callback(
[Output('graph','figure')],
[Input(component_id='FirstDropdown',component_property='value')]
)
def select_graph(value):
if value=='v1':
return fig11
elif value=='v2':
return fig21
elif value=='v3':
return fig31
elif value=='v4':
return fig411
elif value=='v5':
return fig_all
elif value == 'v6':
google_form_iframe = html.Iframe(
width='640px',
height='947px',
src="https://docs.google.com/forms/d/e/1FAIpQLSfkIgHkKlD5Jl4ewfWpA8y9D65UbhdrvZ0k7qXOBI7uFN1aNA/vi ewform?embedded=true"
)
return google_form_iframe
fundamentally dcc.Figure() and html.IFrame() are separate dash components. Hence if you what to display a figure of Iframe based on dropdown use a div container. From callback return child component that fits into this container
to make full working example, have used COVID vaccination data to generate 5 figures that can be selected from drop down.
if google form is selected then return that
import pandas as pd
import plotly.express as px
from jupyter_dash import JupyterDash
import dash
from dash import dcc, html
from dash.dependencies import Input, Output, State
import json
df = pd.read_csv(
"https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/vaccinations/vaccinations.csv"
)
df["date"] = pd.to_datetime(df["date"])
df = df.sort_values(["date", "iso_code"])
figs = {
f"v{n+1}": px.bar(
df.loc[(df["date"].dt.day_of_week == 6) & df["iso_code"].isin(["DEU", "FRA"])],
x="date",
y=c,
color="iso_code",
)
for n, c in zip(range(5), df.select_dtypes("number").columns)
}
# Build App
app = JupyterDash(__name__)
app.layout = dash.html.Div(
[
dcc.Dropdown(
id="FirstDropdown",
options=[
{"label": "graph1", "value": "v1"},
{"label": "graph2", "value": "v2"},
{"label": "graph3", "value": "v3"},
{"label": "graph4", "value": "v4"},
{"label": "graph 5", "value": "v5"},
{"label": "g-form", "value": "v6"},
],
placeholder="Please choose an option",
value="v1",
),
dash.html.Div(
id="graph_container",
),
]
)
#app.callback(
Output("graph_container", "children"),
Input("FirstDropdown", "value"),
)
def select_graph(value):
if value in figs.keys():
return dash.dcc.Graph(figure=figs[value])
else:
return html.Iframe(
width="640px",
height="947px",
src="https://docs.google.com/forms/d/e/1FAIpQLSfkIgHkKlD5Jl4ewfWpA8y9D65UbhdrvZ0k7qXOBI7uFN1aNA/vi ewform?embedded=true",
)
app.run_server(mode="inline")
Related
I would like to create a heat map for different type of users ("segment"), and different day (date)
My code doesn't work and I don't know why. This is the error:
An object was provided as `children` instead of a component, string, or number (or list of those). Check the children property that looks something like:
{
"label": "Mieszkaniec",
"value": "Mieszkaniec"
}
I think the problem is in the layout. Can someone explain me how exactly children work in this example? Maybe it is impossible to do a chained callback for map
import pandas as pd import dash import plotly.express as px import plotly.graph_objects as go from dash import Dash, dcc, html, Input, Output
dane = pd.read_csv("C:\\Users\\fickar00\\Desktop\\Dane\\test2.csv",
encoding = "unicode_escape", sep=";", na_values='-') dane = dane.fillna(0) dane["c_users"] = [float(str(i).replace(",", "")) for i in dane["c_users"]] dane = dane.astype({"c_users": float})
app = Dash(__name__)
app.layout = html.Div([
html.H1('Dobowe przemieszcznie się ludności w Łodzi w interwale godzinowym'),
html.Label("Wybierz segment:"),
dcc.Dropdown(id="wybierz_segment",
options=[
{"label": "Mieszkaniec", "value": "Mieszkaniec"},
{"label": "Regularny gość", "value": "Regularny_gosc"},
{"label": "Turysta", "value": "Turysta"}],
multi=False,
value="Mieszkaniec",
clearable=False,
style={'width': "40%"}
),
html.Label("Wybierz date:"),
dcc.Dropdown(id='wybierz_date',
options=[{'label': s, 'value': s} for s in sorted(dane.day.unique())],
value="01.09.2022",
style={'width': "40%"},
multi=False),
dcc.Graph(id='mapa', figure={})
]) #app.callback(
Output('wybierz_date', 'options'),
Input('wybierz_segment', 'value') ) def ustaw_opcje_segmentu(wybrany_segment):
dff = dane[dane.segment==wybrany_segment]
return [{'label': c, 'value': c} for c in sorted(dff.segment.unique())]
# populate initial values of counties dropdown #app.callback(
Output('wybierz_date', 'value'),
Input('wybierz_date', 'options') ) def ustaw_wartosci_segmentu(dostepne_opcje):
return [x['value'] for x in dostepne_opcje]
#app.callback(
Output('mapa', 'figure'),
Input('wybierz_date', 'value'),
Input('wybierz_segment', 'value') ) def update_grpah(wytypowany_segment, wytypowana_data):
if len(wytypowana_data) == 0:
return dash.no_update
else:
dff = dane[(dane.segment==wytypowany_segment) & (dane.day==wytypowana_data)]
fig = px.density_mapbox(dff,
lat='loc_wgs84_lat',
lon='loc_wgs84_lon',
animation_frame='hour',
animation_group='c_users',
zoom=10,
z='c_users',
height=650,
width=1400,
mapbox_style="carto-darkmatter")
return fig
#fig.write_html("C:\\Karol\\Python\\file.html")
if __name__ == '__main__':
app.run_server(debug=True)
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.
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)
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()
I am trying to have a table load upon clicking a search button, and provide ID/password. My output is a dbc.Table.from_dataframe which allows an df argument; however when I use this as my output property, I am getting an error.
Here are the available properties in "my_table":
['children', 'id', 'style', 'className', 'key', 'tag', 'size', 'bordered', 'borderless', 'striped', 'dark', 'hover', 'responsive', 'loading_state']
I read the docs here
https://dash-bootstrap-components.opensource.faculty.ai/l/components/table
I tried such using 'children' and that didn't work either. I know with dcc table I need to return a dictionary, however I thought with dbc.Table.from_dataframe I can return a dataframe.
#app.callback(Output('my_table', 'df' ),
[Input('search-button','n_clicks')],
[State('input-id', 'value'),
State('input-password', 'value')]
)
def search_fi(n_clicks, iuser, ipasw):
if n_clicks > 0:
df = pd.DataFrame(
{
"First Name": ["Arthur", "Ford", "Zaphod", "Trillian"],
"Last Name": ["Dent", "Prefect", "Beeblebrox", "Astra"],
}
return df
import dash
import dash_html_components as html
import dash_bootstrap_components as dbc
import pandas as pd
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.layout = html.Div([
html.Button('Table', id='table-but', n_clicks=0),
html.Div(id='container-button-basic')
])
#app.callback(
dash.dependencies.Output('container-button-basic', 'children'),
[dash.dependencies.Input('table-but', 'n_clicks')])
def search_fi(n_clicks):
if n_clicks > 0:
df = pd.DataFrame(
{
"First Name": ["Arthur", "Ford", "Zaphod", "Trillian"],
"Last Name": ["Dent", "Prefect", "Beeblebrox", "Astra"]
})
print(df)
return dbc.Table.from_dataframe(df)
if __name__ == '__main__':
app.run_server(debug=True)
or
https://plotly.com/python/table/ figure
Html dash table html-table
Example