How to add name to the DatePickerSingle in Dash/Plotly - python

How do I add label above my DatePickerSingle and Dropdowns?
Scenario is similar to question posted Here just replacing Slider wit
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px
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.Div(className='row', children=[
html.Div(children=[
html.Label(['Dataset:'], style={'font-weight': 'bold', "text-align": "center"}),
dcc.Dropdown(
id='dropdown-dataset',
options=[
{'label': 'Diabetes', 'value': 'diabetes'},
{'label': 'Boston Housing', 'value': 'boston'},
{'label': 'Sine Curve', 'value': 'sin'}
],
value='diabetes',
searchable=False,
clearable=False,
),
html.Label('DatePicker', style={'font-weight': 'bold', "text-align": "center"}),
dcc.DatePickerSingle(
calendar_orientation='vertical',
placeholder='Select a date',
date=date(2017, 6, 21)
),
], style=dict(width='33.33%')),
html.Div(children=[
html.Label(['Model Type'], style={'font-weight': 'bold', "text-align": "center"}),
dcc.Dropdown(
id='dropdown-select-model',
options=[
{'label': 'Linear Regression', 'value': 'linear'},
{'label': 'Lasso', 'value': 'lasso'},
{'label': 'Ridge', 'value': 'ridge'},
{'label': 'Polynomial', 'value': 'polynomial'},
{'label': 'elastic-net', 'value': 'elastic-net'},
],
value='linear',
searchable=False,
clearable=False
),
html.Label('Slider', style={'font-weight': 'bold', "text-align": "center"}),
dcc.Slider(
min=0,
max=9,
marks={i: 'Label {}'.format(i) if i == 1 else str(i) for i in range(1, 6)},
value=5,
),
],style=dict(width='33.33%')),
html.Div(children=[
html.Label(['Add data'], style={'font-weight': 'bold', "text-align": "center"}),
dcc.Dropdown(
id='dropdown-custom-selection',
options=[
{'label': 'Add Training Data', 'value': 'training'},
{'label': 'Add Test Data', 'value': 'test'},
{'label': 'Remove Data point', 'value': 'remove'},
],
value='training',
clearable=False,
searchable=False
),
html.Label('Slider', style={'font-weight': 'bold', "text-align": "center"}),
dcc.Slider(
min=0,
max=9,
marks={i: 'Label {}'.format(i) if i == 1 else str(i) for i in range(1, 6)},
value=5,
),
],style=dict(width='33.33%')),
],style=dict(display='flex')),
)
if name == 'main':
app.run_server(debug=True, port=8080)

Related

How to set a Radio Button Group's width to fill the width of the parent container in Bootstrap?

Is there a way to set Radio Button Groups that span the width of the parent container / dbc.column? I am currently using Dash Plotly and Python to create a web app and the Radio Button Groups I've created in a column of width 2 do not span the width of the column despite numerous attempts. Here's how I am defining the Radio Button Group using the tutorial found at the bottom of the page here.
html.Div([
dbc.RadioItems(
id="pr-select",
className="btn-group d-flex",
labelClassName="btn btn-info",
labelCheckedClassName="active",
style={'width': '100%'},
options=[{'label': 'Opt1', 'value': 'True', 'disabled': 'True'},
{'label': 'Opt2', 'value': 'False', 'disabled': 'True'},
],
),
],
className='radio-group mb-2',
style={'width': '100%'}
),
As you can see, I've already tried setting the width to 100% in the style, however that has had no effect to the width at all. For reference, this is what it outputs on the app. As you can see, all the radio groups span different widths relative to the column they are in. Any help would be greatly appreciated!
EDIT:
I've included sample code below if you would like to reproduce this and play with the CSS. Please also note that the file must be called app.py and must live in a directory with a folder called assets with a mystyle.css file using the custom css listed at the bottom of the page here:
import dash
import dash_core_components as dcc
import dash_bootstrap_components as dbc
import dash_html_components as html
from flask_sqlalchemy import SQLAlchemy
from flask import Flask
server = Flask(__name__)
app = dash.Dash(__name__, server=server,
external_stylesheets=[dbc.themes.FLATLY],
suppress_callback_exceptions=True,
meta_tags=[{'name': 'viewport',
'content': 'width=device-width, initial-scale=1.0'}],
)
app.layout = dbc.Container([
dbc.Row([
dbc.Col([
html.Div([
dbc.RadioItems(
id="hand-select",
className="btn-group",
labelClassName="btn btn-info",
labelCheckedClassName="active",
options=[
{'label': 'Opt1', 'value': 'Left', 'disabled': 'True'},
{'label': 'Opt2', 'value': 'Both', 'disabled': 'True'},
{'label': 'Opt3', 'value': 'Right', 'disabled': 'True'},
],
style={"margin-top": "auto",
}
),
],
className='radio-group mb-2',
style={'width': '100%'}
#style={'max-width': 'fit-content'}
),
html.Div([
dbc.RadioItems(
id="pr-select",
className="btn-group d-flex",
labelClassName="btn btn-info",
labelCheckedClassName="active",
#inputClassName='mw-100',
style={'width': '100%'},
options=[
{'label': 'Opt1', 'value': 'True', 'disabled': 'True'},
{'label': 'Opt2', 'value': 'False', 'disabled': 'True'},
],
),
],
className='radio-group mb-2',
style={'width': '100%'}
),
html.Div([
dbc.RadioItems(
id="cs-select",
className="btn-group",
labelClassName="btn btn-info",
labelCheckedClassName="active",
options=[
{'label': 'Option One.........', 'value': 'True', 'disabled': 'True'},
{'label': 'Option Two.........', 'value': 'False', 'disabled': 'True'},
],
),
],
className='radio-group mb-2'
),
], width=3, style={'margin-right': '0px',
'margin-left': '0px',
'backgroundColor': 'black'},),
dbc.Col([
], width=3),
dbc.Col([
], width=6)
])
]
)
if __name__ == '__main__':
app.run_server(debug=True)
RadioItems generates HTML like this
<div id="pr-select">
<div class="form-check">
<input type="radio" ...>
<label ... >Opt1</label>
</div>
<div class="form-check">
<input type="radio" ...>
<label ... >Opt2</label>
</div>
</div>
And it needs 'width':'100%' in three places:
in external <div id="pr-select"> and this can be added using style={'width':'100%'}
in <label ... > and this can be added using styleLabel={'width':'100%'}
in <div class="form-check"> and this has no method in code.
The only solution which I found is to create file assets/style.css which dash will load automatically
(documentation: Adding CSS & JS and Overriding the Page-Load Template)
.form-check {
width: 100%;
}
assets/style.css
.form-check {
width: 100%;
}
main.py
import dash
from dash import dcc, html
import dash_bootstrap_components as dbc
from flask import Flask
server = Flask(__name__)
app = dash.Dash(__name__, server=server,
external_stylesheets=[dbc.themes.FLATLY],
suppress_callback_exceptions=True,
meta_tags=[{'name': 'viewport',
'content': 'width=device-width, initial-scale=1.0'}],
)
app.layout = dbc.Container([
dbc.Row([
dbc.Col([
html.Div([
dbc.RadioItems(
id="hand-select",
className="btn-group",
labelClassName="btn btn-info",
labelCheckedClassName="active",
inputClassName="btn-check",
options=[
{'label': 'Opt1', 'value': 'Left', 'disabled': 'True'},
{'label': 'Opt2', 'value': 'Both', 'disabled': 'True'},
{'label': 'Opt3', 'value': 'Right', 'disabled': 'True'},
],
style={'width': '100%'}, # <--- for external <div>
labelStyle={'width': '100%'}, # <--- for <input>
)
],
className="radio-group",
style={"margin-top": "5px", "margin-bottom": "5px"}
),
html.Div([
dbc.RadioItems(
id="pr-select",
className="btn-group",
labelClassName="btn btn-info",
labelCheckedClassName="active",
inputClassName="btn-check",
options=[
{'label': 'Opt1', 'value': 'True', 'disabled': 'True'},
{'label': 'Opt2', 'value': 'False', 'disabled': 'True'},
],
style={'width': '100%'}, # <--- for external <div>
labelStyle={'width':'100%'}, # <--- for <input>
)
],
className="radio-group",
style={"margin-top": "5px", "margin-bottom": "5px"}
),
html.Div([
dbc.RadioItems(
id="cs-select",
className="btn-group",
labelClassName="btn btn-info",
labelCheckedClassName="active",
inputClassName="btn-check",
options=[
{'label': 'Option One.........', 'value': 'True', 'disabled': 'True'},
{'label': 'Option Two.........', 'value': 'False', 'disabled': 'True'},
],
style={'width':'100%'}, # <--- for external <div>
labelStyle={'width':'100%'}, # <--- for <input>
)
],
className="radio-group",
style={"margin-top": "5px", "margin-bottom": "5px"}
),
],
width=3, style={'margin-right': '0px',
'margin-left': '0px',
'backgroundColor': 'black'},
),
])
])
if __name__ == '__main__':
#app.debug=True
app.run_server()

Python Dash Dropdown

There are six questions to be asked to the user. If the user answers these questions, I am trying to make an application that will determine the result of which research design to use on the right. I am doing this application with python dash. My Python code is as follows. How do I write a python code that can bring the result of the research design according to the answers given after the user answers the questions? How should I write the callback code in the dash program for this? Thank you so much in advance.
import dash
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
from sympy import *
az = ""
bz = ""
app = dash.Dash(external_stylesheets=[dbc.themes.FLATLY])
app.config.suppress_callback_exceptions = True
logo = "analiz.png"
title = dcc.Link(id='ustbaslik',
href="/",
className="navbar-brand",
style={"margin-top": "12px"})
acıklama = [
dbc.CardHeader(id='acik'),
dbc.CardBody([
html.H5(id='ortabaslik', className="card-title"),
html.P(id='ortamesaj', className="card-text text-justify",),
]),
]
sonuc = [
dbc.CardHeader(id='sonuc'),
dbc.CardBody([
html.P(id='mesaj', className="card-text text-justify",),
]),
]
app.layout = html.Div([
html.Nav([
dbc.Container([
dbc.Row([
dbc.Col(title, align="left",width="auto"),
dbc.Col("", align="left",width="%100"),
],
justify="between",
align="center",
),
dbc.Row([
dbc.Col(
html.Div([
html.Button('Türkçe', id='btn-nclicks-1'),
html.Button('İngilizce', id='btn-nclicks-2'),
])
),
],
justify="between",
align="center",
)
])
],
className="navbar navbar-dark bg-dark navbar-expand-md bg-light sticky-top",
),
dbc.Container(
dbc.Row([
dbc.Col(dbc.Card(acıklama, color="primary", inverse=True)),
dbc.Col(
html.Div(children=[
html.Label('Araştırmadaki Değişken Türünü Giriniz:'),
dcc.Dropdown(
options=[
{'label': 'Nitel', 'value': 'nitel'},
{'label': 'Nicel', 'value': 'nicel'}
],
value='tur'
),
html.Hr(),
html.Label('Girişim var mı'),
dcc.Dropdown(
options=[
{'label': 'Evet', 'value': 'evet'},
{'label': 'Hayır', 'value': 'hayır'}
],
value='gir'
),
html.Hr(),
html.Label('Hipotez var mı:'),
dcc.Dropdown(
options=[
{'label': 'Evet', 'value': 'evet'},
{'label': 'Hayır', 'value': 'hayır'}
],
value='hip'
),
html.Hr(),
html.Label('Hasta sayısı:'),
dcc.Dropdown(
options=[
{'label': 'Bir hasta', 'value': 'bir'},
{'label': 'Birden fazla hasta', 'value': 'birden'},
{'label': 'Bir grup hasta', 'value': 'grup'}
],
value='has'
),
html.Hr(),
html.Label('Araştırma sorusunun yönü:'),
dcc.Dropdown(
options=[
{'label': 'Yok', 'value': 'yok'},
{'label': 'Geriye', 'value': 'geri'},
{'label': 'İleriye', 'value': 'ileri'}
],
value='yon'
),
html.Hr(),
html.Label('Araştırmadan elde edilen ölçüt:'),
dcc.Dropdown(
options=[
{'label': 'Prevelans Hızı', 'value': 'pre'},
{'label': 'Olasılık Oranı', 'value': 'ola'},
{'label': 'İnsidans Hızı', 'value': 'hız'}
],
value='eld'
),
])
),
dbc.Col(dbc.Card(sonuc, color="primary", inverse=True)
)],
style={"margin-top": "50px"},
),
),
html.Hr(),
dcc.Location(id='url', refresh=False),
html.Div(id='page-content'),
])
#app.callback([
Output('ustbaslik', 'children'),
Output('ortabaslik', 'children'),
Output('ortamesaj', 'children'),
Output('acik', 'children'),
Output('sonuc', 'children')
],
[
Input('btn-nclicks-1', 'n_clicks'),
Input('btn-nclicks-2', 'n_clicks')
])
def displayClick(btn1, btn2):
changed_id = [p['prop_id'] for p in dash.callback_context.triggered][0]
if 'btn-nclicks-1' in changed_id:
ustbaslik = 'EPİDEMİYOLOJİK DENEY TASARIMLARI'
ortabaslik = 'Epidemiyolojik Deney Tasarımları'
ortamesaj = 'Epidemiyolojik araştırmalar, hastalıkların ...'
acik = 'Açıklama'
sonuc = 'Araştırma Tasarımınız ...'
elif 'btn-nclicks-2' in changed_id:
ustbaslik = 'EPIDEMIOLOGICAL EXPERIMENT DESIGN'
ortabaslik = 'Theoretical Probability Distributions Software'
ortamesaj = 'Epidemiological research, diseases and ...'
acik = 'Explanation'
sonuc ='Your Research Design ...'
else:
ustbaslik = 'EPİDEMİYOLOJİK DENEY TASARIMLARI'
ortabaslik = 'Epidemiyolojik Deney Tasarımları'
ortamesaj = 'Epidemiyolojik araştırmalar, hastalıkların ...'
acik = 'Açıklama'
sonuc = 'Araştırma Tasarımınız ...'
return ustbaslik,ortabaslik,ortamesaj,acik,sonuc
if __name__ == '__main__':
app.run_server(debug=True)
You need to make a couple of changes. Firstly you need to give your dropdown an id:
dcc.Dropdown(id='dropdown1',
options=[{'label': 'Nitel', 'value': 'nitel'},
{'label': 'Nicel', 'value': 'nicel'}],
value='tur'),
I've given it an id of 'dropdown1'
I also added a container for the output just to show the callback working:
html.Div(id='dd-output-container'),
Then the callback is simply:
#app.callback(
Output('dd-output-container', 'children'),
[Input('dropdown1', 'value')],
)
def dropdown1_callback(v):
return v
Hope this helps. More help can be found here

How to place dropdowns side by side in Dash,Python

I'm pretty new to dash and trying to place two dropdowns side by side each other but they don't seem to work at all, instead they are below each other. I think I'm messing up in 'className' arrangement of HTML div's. The code is as follows:
app.layout = html.Div([
html.Div( [
html.H1("Web Application Dashboards with Dash", style={'text-align': 'center'}),
] ),
html.Div(
className = "row",children =[
html.Div(className='six columns', children=[
dcc.Dropdown(
id='dropdown_dataset',
options=[
{'label': 'diabetes', 'value': 'diabetes'},
{'label': 'Custom Data', 'value': 'custom'},
{'label': 'Linear Curve', 'value': 'linear'},
],
value='diabetes',
clearable=False,
searchable=False,
)])
,html.Div(className='six columns', children=[
dcc.Dropdown(
id='dropdown_dataset_2',
options=[
{'label': 'sinh', 'value': 'sinh'},
{'label': 'tanh', 'value': 'cosh'},
],
value='diabetes',[![enter image description here][1]][1]
clearable=False,
searchable=False,
)])
])
])
if __name__ == '__main__':
app.run_server(host='127.0.0.1',port = '5000',debug=False,use_reloader=False)
Can you point where I'm making the mistake and is there any documentation to refer for this ?
This will do it. I've added display='flex' to the div that contains both dropdowns, and set the width to 50% for the divs that contain only single dropdowns. You could certainly set those styles in your CSS file using the IDs or classnames instead of coding them inline like this.
html.Div(
className="row", children=[
html.Div(className='six columns', children=[
dcc.Dropdown(
id='dropdown_dataset',
options=[
{'label': 'diabetes', 'value': 'diabetes'},
{'label': 'Custom Data', 'value': 'custom'},
{'label': 'Linear Curve', 'value': 'linear'},
],
value='diabetes',
clearable=False,
searchable=False,
)], style=dict(width='50%'))
, html.Div(className='six columns', children=[
dcc.Dropdown(
id='dropdown_dataset_2',
options=[
{'label': 'sinh', 'value': 'sinh'},
{'label': 'tanh', 'value': 'cosh'},
],
value='diabetes', # [![enter image description here][1]][1]
clearable=False,
searchable=False,
)], style=dict(width='50%'))
], style=dict(display='flex'))

Python Dash: Function should not run when n_clicks < 0 and defined in a call back

I am working on plotly dash app. I have an almost working example. The only thing that is not working is that I am not able to restrict the functions defined in the callbacks not to run when the page loads.
I have tried add checks for the n_clicks inside the callback however it doesnt seem to be working. It runs the function without the clicks as well
Below is the code for the dash
from datetime import date
import base64
import dash
import plotly
import dash
from dash.dependencies import Input, Output, State
from plotly.graph_objs import *
from datetime import datetime as dt
import dash_html_components as html
import dash_core_components as dcc
import flask
import pandas as pd
server = flask.Flask('app')
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash('app', server=server, external_stylesheets=external_stylesheets)
app.layout = html.Div(style={'backgroundColor': '#EFEAEA', 'margin': '0px', 'padding': '0px'}, children=[
html.Div([
html.Div([
html.Img(src='data:image/png;base64,{}'.format(encoded_image.decode()),
style={'width': '200px', 'height': '100px', 'display': 'inline-block', 'float': 'left', 'padding-left': '5px', 'padding-top': '5px'})
]),
html.Div([
html.Div([
html.Div([
dcc.Dropdown(
id='demographics',
options=[
{'label': 'All 18-49', 'value': '18_39'},
{'label': 'Female 25-54', 'value': '25_54 F'},
{'label': 'All 25-54', 'value': '25-54'},
],
placeholder="Select Demographics",
)
],
style={'width': '30.5%', 'display': 'inline-block', 'padding-right': '10px'}),
html.Div([
dcc.DatePickerRange(
id='my-date-picker-range',
start_date_placeholder_text="Select a Start Date",
end_date_placeholder_text="Select an End Date",
min_date_allowed=dt(2018, 1, 1),
max_date_allowed=dt(2050, 12, 31),
initial_visible_month=dt(2019, 1, 2),
style={'width': '600', 'display': 'inline-block', 'padding-right': '10px'}
),
html.Div(id='output-container-date-picker-range')
],
style={'width': '30.3%', 'display': 'inline-block', 'padding-right': '10px', 'position': 'relative'})
],
style={
'backgroundColor': '#EFEAEA',
'padding': '5px 10px'}),
html.Div([
html.Div([
dcc.Dropdown(
id='Horsepower',
options=[
{'label': '200', 'value': 'two_hundred'},
{'label': '250', 'value': 'two_hundred_fifty'},
{'label': '300', 'value': 'three_hundred'},
{'label': '350', 'value': 'three_hundred_fifty'},
{'label': '400', 'value': 'four_hundred'}
],
placeholder="Select TARP",
)
],
style={'width': '20%', 'display': 'inline-block', 'padding-right': '10px'}),
html.Div([
dcc.Dropdown(
id='Kilometers',
options=[
{'label': '250,000', 'value': 250000, 'type': 'number'},
{'label': '500,000', ''value': 500000, 'type': 'number'},
{'label': '750,000', 'value': 750000, 'type': 'number'},
{'label': '1,000,000', 'value': 1000000, 'type': 'number'},
],
placeholder="Select Impressions",
)
],
style={'width': '20%', 'display': 'inline-block', 'padding-right': '10px'}),
html.Div([
dcc.Dropdown(
id='Speed',
options=[
{'label': 'Low', 'value': 50, 'type': 'number'},
{'label': 'Average', 'value': 100, 'type': 'number'},
{'label': 'High', 'value': 150, 'type': 'number'},
],
placeholder="Select Frequency",
)
],
style={'width': '20%', 'display': 'inline-block', 'padding-right': '10px'}),
html.Div([
html.Button('Submit', id='submit_button', type='submit', n_clicks=1,
style={'width': '100px', 'height': '34.5px', 'margin-bottom': '8px',
'border-radius': '4px', 'display': 'inline-block', 'background-color': '#2D91C3', 'color': 'white'})
],
style={'display': 'inline-block', 'padding-bottom': '20px', 'verticalAlign': 'middle'}),
], style={
'backgroundColor': '#EFEAEA',
'padding': '5px'})
], style={'position': 'relative', 'left': '250px'})
]),
html.Div([
html.Div([
dcc.Graph(id='example-graph', config={'modeBarButtonsToRemove': ['pan2d', 'lasso2d', 'sendDataToCloud',
'select2d', 'autoScale2d', 'resetScale2d',
'toggleSpikelines',
'hoverClosestCartesian']})
],
style={'width': '49.3%', 'display': 'inline-block', 'border': 'thin grey solid', 'margin-left': '5px',
'margin-right': '2.5px', 'margin-top': '5px', 'margin-bottom': '2.5px'}),
html.Div([
dcc.Graph(id='example-graph1')
],
style={'width': '49.3%', 'display': 'inline-block', 'border': 'thin grey solid', 'margin-left': '2.5px',
'margin-right': '5px', 'margin-top': '5px', 'margin-bottom': '2.5px', 'backgroundColor': '#EFEAEA'})
], style={'backgroundColor': '#EFEAEA'}),
html.Div([
dcc.Graph(id='graph1')
],
style={'width': '99.2%', 'height': '120%', 'display': 'inline-block', 'border': 'thin grey solid', 'margin-left': '2.5px',
'margin-right': '5px', 'margin-top': '5px', 'margin-bottom': '2.5px', 'backgroundColor': '#EFEAEA'})
])
#app.callback(Output('example-graph1', 'figure'),
[Input('submit_button', 'n_clicks')],
[State('my-date-picker-range', 'start_date'),
State('my-date-picker-range', 'end_date')])
def update_graph(n_clicks, start_date, end_date):
if n_clicks > 0:
df = df_new
start_date_temp = dt.strptime(start_date, '%Y-%m-%d')
end_date_temp = dt.strptime(end_date, '%Y-%m-%d')
start_date_new = start_date_temp.replace(start_date_temp.year - 1)
end_date_new = end_date_temp.replace(end_date_temp.year - 1)
end_date_string = end_date_new.strftime('%Y-%m-%d')
start_date_string = start_date_new.strftime('%Y-%m-%d')
mask = (df['Date'] >= start_date_string) & (df['Date'] <= end_date_string)
filtered_df = df.loc[mask]
trace = Scatter(
y=filtered_df['Weights'],
x=filtered_df['Date'],
line=plotly.graph_objs.scatter.Line(
color='#42C4F7'
),
hoverinfo='skip',
error_y=plotly.graph_objs.scatter.ErrorY(
type='data',
array=filtered_df['Gender'],
thickness=1.5,
width=2,
color='#B4E8FC'
),
mode='lines'
)
layout1 = Layout(
height=450,
xaxis=dict(
showgrid=False,
showline=False,
zeroline=False,
fixedrange=True,
title='Time Elapsed (sec)'
),
yaxis=dict(
showline=False,
fixedrange=True,
zeroline=False,
),
margin=plotly.graph_objs.layout.Margin(
t=45,
l=50,
r=50
)
)
return Figure(data=[trace], layout=layout1)
else:
return {"I am the boss"}
The reason I presume the n_clicks checks is not working because I get the following error
TypeError: strptime() argument 1 must be str, not None
I believe the error is because of the below code inside the function as the first time the page loads start_date would be none type.
start_date_temp = dt.strptime(start_date, '%Y-%m-%d')
Can some one please help to resolve the issue. What I expect that when the page loads the call back function should not run.
Thanks a lot in advance !!
Here is your problem:
html.Button('Submit', id='submit_button', type='submit', n_clicks=1,
You've preset n_clicks to have a value. Just remove that n_clicks=1 part, and it will load the page as None. You will then need to check n_clicks like this (or similar):
if n_clicks is not None and n_clicks > 0:
It worked for me, and ran until it broke with my example df.

Dynamically Adding Traces In Plotly With A Checklist

I have a dataset with different age ranges as different columns. I am trying to create dynamic traces for each age range in Plotly to create a comparative bar chart. Moreover, I would like these traces to be connected to a checklist, so I can choose which traces/bars to show up in the resulting graph. However, I am having trouble figuring out how to connect this checklist to the resulting traces in the graph especially since I have other dropdown connected to this graph as well. Here is a sample of the code
Gender=xl['Gender'].unique()
Age=xl['Age'].unique()
Activity=xl['Sport'].unique()
app=dash.Dash(__name__)
app.layout=html.Div(children=
[html.Div([
html.H3('Age:', style={'paddingRight': '30px','fontSize':18}),
dcc.Checklist(
id='Age',
options=[
{'label': i, 'value': i} for i in Age],
value='18-24'
)], style={'width':'33%','display':'inline-block'}),
html.Div([
html.H3('Gender:', style={'paddingRight': '30px','fontSize':18}),
dcc.Dropdown(
id='Gender',
options=[
{'label': 'Male', 'value': 'Male'},
{'label': 'Female', 'value': 'Female'}
],
value='Male'
)], style={'width':'33%','display':'inline-block'}),
html.H3('Activity:', style={'paddingRight': '30px','fontSize':18}),
dcc.Dropdown(
id='Sport',
options=[
{'label': i, 'value': i} for i in Activity],
value='Yoga'
),
],style={'width':'33%','display':'inline-block'}),
html.Div([
dcc.Graph(id='linear')]),
html.Div([
dcc.Graph(id='linear2')
])])
#app.callback(
dash.dependencies.Output('linear','figure'),
[dash.dependencies.Input('Gender','value'),
dash.dependencies.Input('Sport','value'),
dash.dependencies.Input('Age','value')])
def update_graph(Gender_name,sport_name,age_name):
xl1=xl[xl['Gender'] == Gender_name]
xl2=xl1[xl1['Sport'] == sport_name]
xl3=xl2[xl2['Age'] == age_name]
Total_x=xl3.Date
trace1=go.Bar(x=Total_x,y=age_name?,name='6-12')
trace2=go.Bar(x=Total_x,y=age_name?,name='12-18')
trace3=go.Bar(x=Total_x,y=age_name,name='18-24')
Totallayout=go.Layout(xaxis={'title': 'Year'},
yaxis={'title': 'Participants'},
title= 'Core Player Comparison',
hovermode='closest')
return {'data':[trace2,trace1,trace3],
'layout':[Totallayout]}
I was hoping if someone could help me with the def update graph function so that it could link back to the age dropdown I created while creating different traces as well. If anyone could help, that would be greatly appreciated, thanks!
Sample Dataframe:
Date Sport Gender Age Players Core
2008 Yoga Male 6-12 2308.54 692.562
2008 Yoga Male 13-17 3551.60 1065.480
2008 Yoga Male 18-24 2663.70 799.110
2008 Yoga Male 25-34 3551.60 1065.480
2008 Yoga Male 35-44 2130.96 639.288
Idea is to create a graph where "Players" or "Core" is the Y Axis and Date is the x axis with Age being the traces.
Thanks for updating with the sampledf. I'm not sure exactly what your goal is, but I have data flowing through and charting the df. Here is a functional example:
dict_form = {
'Date': [2008, 2008, 2008, 2008, 2008],
'Sport': ['Yoga', 'Yoga', 'Yoga', 'Yoga', 'Yoga'],
'Gender': ['Male', 'Male', 'Male', 'Male', 'Male'],
'Age': ['6-12', '13-17', '18-24', '25-34', '35-44'],
'Players': [2308.54, 3551.60, 2663.70, 3551.60, 2130.96],
'Core': [692.562, 1065.480, 799.110, 1065.480, 639.288],
}
df = pandas.DataFrame.from_dict(dict_form)
app = dash.Dash(__name__)
app.layout = html.Div(children=[
html.Div(children=[
html.H3('Age:', style={'paddingRight': '30px', 'fontSize': 18}),
dcc.Checklist(
id='Age',
options=[
{'label': i, 'value': i} for i in df['Age']],
values=['18-24']
)
]),
html.Div(children=[
html.H3('Gender:', style={'paddingRight': '30px', 'fontSize': 18}),
dcc.Dropdown(
id='Gender',
options=[
{'label': 'Male', 'value': 'Male'},
{'label': 'Female', 'value': 'Female'}
],
value='Male'
)
], style={'width': '33%', 'display': 'inline-block'}),
html.H3('Activity:', style={'paddingRight': '30px', 'fontSize': 18}),
dcc.Dropdown(
id='Sport',
options=[
{'label': i, 'value': i} for i in df['Sport']],
value='Yoga'
),
html.Div([
dcc.Graph(id='linear')]),
html.Div([
dcc.Graph(id='linear2')
])
], style={'width': '33%', 'display': 'inline-block'})
#app.callback(
dash.dependencies.Output('linear', 'figure'),
[dash.dependencies.Input('Gender', 'value'),
dash.dependencies.Input('Sport', 'value'),
dash.dependencies.Input('Age', 'values')])
def update_graph(gender_name, sport_name, age_name):
df1 = df[df['Gender'] == gender_name]
df2 = df1[df1['Sport'] == sport_name]
df3 = df2[df2['Age'].isin(age_name)]
total_x = df3.Age
trace1 = go.Bar(x=total_x, y=df3['Players'], name='Players')
trace2 = go.Bar(x=total_x, y=df3['Core'], name='Core')
total_layout = go.Layout(xaxis={'title': 'Year'},
yaxis={'title': 'Participants'},
title='Core Player Comparison',
hovermode='closest')
return {'data': [trace2, trace1],
'layout': [total_layout]}
if __name__ == '__main__':
app.run_server(debug=True, threaded=True)
And here is a screencap of the chart:

Categories

Resources