Dynamically Adding Traces In Plotly With A Checklist - python

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:

Related

How to return multiple markers for dash leaflet map based on the current page rows in a datatable

So I've tried many iterations of returning a for loop for this code everything else appears to be working as intended. I'll try to just include relevant code snips.
'''
dcc.Dropdown(
id='select_page_size',
options=[
{'label': '5', 'value': 5},
{'label': '10', 'value': 10},
{'label': '15', 'value': 15},
{'label': '20', 'value': 20},
],
# Default value for results per page.
value=10,
style=dict(width='40%', verticalAlign="middle")
)
dcc.RadioItems(
id='filter-type',
options=[
{'label': 'Water Rescue', 'value': 'water_filter'},
{'label': 'Mountain Rescue', 'value': 'mountain_filter'},
{'label': 'Disaster Rescue', 'value': 'disaster_filter'},
{'label': 'Reset', 'value': 'no_filter'},
],
value='no_filter',
labelStyle={'display': 'inline-block'}
)
dt.DataTable(
id='datatable-id',
columns=[
{"name": i, "id": i, "deletable ": False, "selectable ": True} for i in df.columns
],
filter_action='native',
sort_action='native',
page_action='native',
page_current=0,
page_size=PAGE_SIZE,
data=df.to_dict('records'),
)
#app.callback(
Output('map-id', 'children'),
[Input('datatable-id', 'derived_viewport_data')]
)
# Function of geolocation chart callback
def update_map(viewData):
dff = pd.DataFrame.from_dict(viewData)
# Austin TX is at [30.75,-97.48]
return [
dl.Map(style={'width': '1000px', 'height': '500px'}, center=[30.75,-97.48], zoom=10, children=[
dl.TileLayer(id="base-layer-id"),
# Marker with tool tip and popup
# for i in range page_size:
# create marker at i position long,lang
dl.Marker(position=[30.75,-97.48], children=[
dl.Tooltip(dff.iloc[0,4]),
dl.Popup([
html.H3("Animal Name"),
html.P(dff.iloc[0,8])
])
])
])
]
'''
Ideally when the datatable is updated with either the page or a filter option attached to a radioItem I could have multiple markers on the map show a latitude and longitude iloc[i,14] iloc[i, 15]. I assumed the way I would do that is with for i in range page_size.

How to add name to the DatePickerSingle in Dash/Plotly

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)

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'))

Create a dash graph with dropdown menu

Hi I have an excel file that looks like this where there are three diferent servers (A, B, C).
I am trying to build a dash app that has a dropdown menu which will make it possible to select the desired server and display the graph for CPU Usage and Memory Usage for each server.
I have tried to modify the following code from the official Dash website. Data can be found on https://plotly.github.io/datasets/country_indicators.csv
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import pandas as pd
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
df = pd.read_csv('https://plotly.github.io/datasets/country_indicators.csv')
available_indicators = df['Indicator Name'].unique()
app.layout = html.Div([
html.Div([
html.Div([
dcc.Dropdown(
id='xaxis-column',
options=[{'label': i, 'value': i} for i in available_indicators],
value='Fertility rate, total (births per woman)'
),
dcc.RadioItems(
id='xaxis-type',
options=[{'label': i, 'value': i} for i in ['Linear', 'Log']],
value='Linear',
labelStyle={'display': 'inline-block'}
)
],
style={'width': '48%', 'display': 'inline-block'}),
html.Div([
dcc.Dropdown(
id='yaxis-column',
options=[{'label': i, 'value': i} for i in available_indicators],
value='Life expectancy at birth, total (years)'
),
dcc.RadioItems(
id='yaxis-type',
options=[{'label': i, 'value': i} for i in ['Linear', 'Log']],
value='Linear',
labelStyle={'display': 'inline-block'}
)
],style={'width': '48%', 'float': 'right', 'display': 'inline-block'})
]),
dcc.Graph(id='indicator-graphic'),
dcc.Slider(
id='year--slider',
min=df['Year'].min(),
max=df['Year'].max(),
value=df['Year'].max(),
marks={str(year): str(year) for year in df['Year'].unique()},
step=None
)
])
#app.callback(
Output('indicator-graphic', 'figure'),
[Input('xaxis-column', 'value'),
Input('yaxis-column', 'value'),
Input('xaxis-type', 'value'),
Input('yaxis-type', 'value'),
Input('year--slider', 'value')])
def update_graph(xaxis_column_name, yaxis_column_name,
xaxis_type, yaxis_type,
year_value):
dff = df[df['Year'] == year_value]
return {
'data': [dict(
x=dff[dff['Indicator Name'] == xaxis_column_name]['Value'],
y=dff[dff['Indicator Name'] == yaxis_column_name]['Value'],
text=dff[dff['Indicator Name'] == yaxis_column_name]['Country Name'],
mode='markers',
marker={
'size': 15,
'opacity': 0.5,
'line': {'width': 0.5, 'color': 'white'}
}
)],
'layout': dict(
xaxis={
'title': xaxis_column_name,
'type': 'linear' if xaxis_type == 'Linear' else 'log'
},
yaxis={
'title': yaxis_column_name,
'type': 'linear' if yaxis_type == 'Linear' else 'log'
},
margin={'l': 40, 'b': 40, 't': 10, 'r': 0},
hovermode='closest'
)
}
if __name__ == '__main__':
app.run_server(debug=True)
The ouput of this code gives an output similar to mine except that the second drop down menu and the slicer would not be needed
I am struggling to understand how to modify the code to be able to apply to mine. Any help would be welcome. Thank you.
Your callback func will have a single Output and a single Input. The output will be the figure of the graph, and the input will be the value of the dropdown.
In your callback, you can filter the dataframe you build from the Excel file something like this:
df = pandas.read_excel('path/to/my/file.xlsx')
df = df[df['server'].eq(dropdown_value)]
From there just fit the data into the dict that represents the figure much like it's done in the Dash example and return it.

How to update xaxis and yaxis name on interval using Dash Plotly in python?

I copy the example from Dash-Plotly multiple inputs (https://dash.plot.ly/getting-started-part-2) and I changed it to be updated on intervals of 2 seconds. The graph is being updated but the title on the X and Y axis are not. The original example updates the X and Y titles on the graph. I am using python 3. I realized that this is happening only because I am using dcc.Graph(id='indicator-graphic', animate=True),. If I use dcc.Graph(id='indicator-graphic'), the xaxis and yaxis are updated but the graph itself no. Here is the code:
import dash
from dash.dependencies import Output, Input, Event
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import plotly.graph_objs as go
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
df = pd.read_csv(
'https://gist.githubusercontent.com/chriddyp/'
'cb5392c35661370d95f300086accea51/raw/'
'8e0768211f6b747c0db42a9ce9a0937dafcbd8b2/'
'indicators.csv')
available_indicators = df['Indicator Name'].unique()
# load file with all RPi available
available_rpi = pd.read_csv('available_rpi.conf', header=None, dtype={0: str}).set_index(0).squeeze().to_dict()
print("Raspberry Pi's available:")
for key, value in available_rpi.items():
print('IP:{} name: {}'.format(key, value))
print()
app.layout = html.Div([
html.Div([
html.Div([
dcc.Dropdown(
id='xaxis-column',
options=[{'label': i, 'value': i} for i in available_indicators],
value='Fertility rate, total (births per woman)'
),
dcc.RadioItems(
id='xaxis-type',
options=[{'label': i, 'value': i} for i in ['Linear', 'Log']],
value='Linear',
labelStyle={'display': 'inline-block'}
)
],
style={'width': '30%', 'display': 'inline-block'}),
html.Div([
dcc.Dropdown(
id='yaxis-column',
options=[{'label': i, 'value': i} for i in available_indicators],
value='Life expectancy at birth, total (years)'
),
dcc.RadioItems(
id='yaxis-type',
options=[{'label': i, 'value': i} for i in ['Linear', 'Log']],
value='Linear',
labelStyle={'display': 'inline-block'}
)
],style={'width': '30%', 'float': 'right', 'display': 'inline-block'})
]),
dcc.Graph(id='indicator-graphic', animate=True),
dcc.Interval(id='graph-update',interval=2*1000),
dcc.Slider(
id='year--slider',
min=df['Year'].min(),
max=df['Year'].max(),
value=df['Year'].max(),
marks={str(year): str(year) for year in df['Year'].unique()}
)
])
#app.callback(
dash.dependencies.Output('indicator-graphic', 'figure'),
[dash.dependencies.Input('xaxis-column', 'value'),
dash.dependencies.Input('yaxis-column', 'value'),
dash.dependencies.Input('xaxis-type', 'value'),
dash.dependencies.Input('yaxis-type', 'value'),
dash.dependencies.Input('year--slider', 'value')],
events=[Event('graph-update', 'interval')])
def update_graph(xaxis_column_name, yaxis_column_name,
xaxis_type, yaxis_type,
year_value):
dff = df[df['Year'] == year_value]
return {
'data': [go.Scatter(
x=dff[dff['Indicator Name'] == xaxis_column_name]['Value'],
y=dff[dff['Indicator Name'] == yaxis_column_name]['Value'],
text=dff[dff['Indicator Name'] == yaxis_column_name]['Country Name'],
mode='markers',
marker={
'size': 15,
'opacity': 0.5,
'line': {'width': 0.5, 'color': 'white'}
}
)],
'layout': go.Layout(
xaxis={
'title': xaxis_column_name,
'type': 'linear' if xaxis_type == 'Linear' else 'log'
},
yaxis={
'title': yaxis_column_name,
'type': 'linear' if yaxis_type == 'Linear' else 'log'
},
margin={'l': 40, 'b': 40, 't': 10, 'r': 0},
hovermode='closest'
)
}
if __name__ == '__main__':
app.run_server(debug=True)
according to https://community.plot.ly/t/my-callback-is-updating-only-the-lines-of-the-graph-but-not-the-legend/16208/3?u=felipe.o.gutierrez there is a lot of issues with animate=True and they are replacing for Exploring a "Transitions" API for dcc.Graph 2

Categories

Resources