Python-Dash dropdown display of multiple items with interactive callbacks - python

I am using Dash by Plotly with python to create a web application.
I have been struggling with having multiple values being displayed correctly on a dropdown element. Starting from a pandas dataframe I am extracting a column 1, then selecting values in another column 2 corresponding to values in column 1. Multiple values are to be displayed in the dropdown. Attached is a GIF of what the app is doing. I want the values on dropdown 2 to be independent values on separate lines, i.e distinct values and not concatenated together.
I think the problem is how I am returning the values in
def update_dropdown2(wdg):
wdgarray=df[ df['wdg'] == wdg ]['id'],
return [{'label':i,'value':i} for i in wdgarray]
Here is a gif file showing the problem of the
second dropdown element display on each line
Here is the code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
from dash.dependencies import Input, Output
#create a dataframe with random data
df = pd.DataFrame(
{'wdg': [10,10,10,20,20,20,30,30,30,40],
'id': np.arange(0,100,10),
'b': np.random.rand(10)*100,
'c': np.random.rand(10)*100,
'd': np.random.rand(10)*100,
'e': np.random.rand(10)*100,
'f': np.random.rand(10)*100,
'g': np.random.rand(10)*100,
'h': np.random.rand(10)*100,
'k': np.random.rand(10)*100},
columns=['wdg','id','b','c','d','e','f','g','h','k'])
app = dash.Dash()
#html layout
app.layout = html.Div([
html.H1(
children='Perfomance database web app',
style={
'textAlign': 'center',
'color': colors['text']}
),
html.Div([
dcc.Dropdown(
id='dropdown1',
options=[{'label': i, 'value': i} for i in df.wdg.unique()],
value='10'
),
dcc.Dropdown(
id='dropdown2',
#options=[{'label': i, 'value': i} for i in mtrid_indicators],
#value='1'
),
],
style={'width': '49%', 'display': 'inline-block'}
),
html.Div(id='tablecontainer'),
html.Div(
dcc.Graph(
id='graph',
style={'width':'600','height':'500'}
),
style={'display':'inline-block'}
),
],
style={'width': '100%', 'display': 'inline-block'}
)
#callback to update dropdown 2
#app.callback(
Output(component_id='dropdown2',component_property='options'),
[Input(component_id='dropdown1',component_property='value')]
)
#function to that will update values in dropdown 2
def update_dropdown2(wdg):
wdgarray=df[ df['wdg'] == wdg ]['id'],
return [{'label':i,'value':i} for i in wdgarray]
#callback to update graph with values of dropdown 1 selecting pandas row
#app.callback(
Output('graph', 'figure'),
[Input('dropdown1', 'value')]
)
#graph plot and styling
def update_graph(row):
dff = df.iloc[int(row/10)].values # update with your own logic
return {
'data': [
go.Scatter(
x=np.arange(0,80,10),
y=dff,
mode='lines+markers',
line = dict(width = 5,color = 'rgb(200, 0, 0)'),
name='Torque curve',
marker = dict(
size = 10,
color = 'rgba(200, 0, 0, .9)',
line = dict(width = 2,color='rgb(0, 0, 0)')
)
),
],
'layout': go.Layout(
title='Torque Speed curve',
xaxis=dict(
# type='line',
title='Speed - (RPM)',
showgrid=True,
#zeroline=True,
showline=True,
gridcolor='#bdbdbd',
mirror="ticks",
ticks="inside",
tickwidth=1,
linewidth=2,
range=[0,100]
),
yaxis=dict(
title= 'Torque - (lb-ft)',
titlefont=dict( color='rgb(200, 0, 0)' ),
tickfont=dict( color='rgb(200, 0, 0)' ),
range=[0, 120],
showgrid=True,
#zeroline=True,
showline=True,
gridcolor='#bdbdbd',
mirror="ticks",
ticks="inside",
tickwidth=1,
linewidth=2
),
margin={'l': 60, 'b': 40, 't': 30, 'r': 60},
#legend={'x': 0.5, 'y': 1},
hovermode='closest',
showlegend=False,
)
}
if __name__ == '__main__':
app.run_server()

Solution coming from pdh in the amazing plotly community is to remove the comma which is turning what should be a pandas series into a tuple.
Link to solution from Plotly community
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
from dash.dependencies import Input, Output
#create a dataframe with random data
df = pd.DataFrame(
{'wdg': [10,10,10,20,20,20,30,30,30,40],
'id': np.arange(0,100,10),
'b': np.random.rand(10)*100,
'c': np.random.rand(10)*100,
'd': np.random.rand(10)*100,
'e': np.random.rand(10)*100,
'f': np.random.rand(10)*100,
'g': np.random.rand(10)*100,
'h': np.random.rand(10)*100,
'k': np.random.rand(10)*100},
columns=['wdg','id','b','c','d','e','f','g','h','k'])
app = dash.Dash()
#html layout
app.layout = html.Div([
html.H1(
children='Perfomance database web app',
style={
'textAlign': 'center',
'color': colors['text']}
),
html.Div([
dcc.Dropdown(
id='dropdown1',
options=[{'label': i, 'value': i} for i in df.wdg.unique()],
value='10'
),
dcc.Dropdown(
id='dropdown2',
#options=[{'label': i, 'value': i} for i in mtrid_indicators],
#value='1'
),
],
style={'width': '49%', 'display': 'inline-block'}
),
html.Div(id='tablecontainer'),
html.Div(
dcc.Graph(
id='graph',
style={'width':'600','height':'500'}
),
style={'display':'inline-block'}
),
],
style={'width': '100%', 'display': 'inline-block'}
)
#callback to update dropdown 2
#app.callback(
Output(component_id='dropdown2',component_property='options'),
[Input(component_id='dropdown1',component_property='value')]
)
#function to that will update values in dropdown 2
def update_dropdown2(wdg):
wdgarray=df[ df['wdg'] == wdg ]['id'] # removed problematic comma
return [{'label':i,'value':i} for i in wdgarray]
#callback to update graph with values of dropdown 1 selecting pandas row
#app.callback(
Output('graph', 'figure'),
[Input('dropdown1', 'value')]
)
#graph plot and styling
def update_graph(row):
dff = df.iloc[int(row/10)].values # update with your own logic
return {
'data': [
go.Scatter(
x=np.arange(0,80,10),
y=dff,
mode='lines+markers',
line = dict(width = 5,color = 'rgb(200, 0, 0)'),
name='Torque curve',
marker = dict(
size = 10,
color = 'rgba(200, 0, 0, .9)',
line = dict(width = 2,color='rgb(0, 0, 0)')
)
),
],
'layout': go.Layout(
title='Torque Speed curve',
xaxis=dict(
# type='line',
title='Speed - (RPM)',
showgrid=True,
#zeroline=True,
showline=True,
gridcolor='#bdbdbd',
mirror="ticks",
ticks="inside",
tickwidth=1,
linewidth=2,
range=[0,100]
),
yaxis=dict(
title= 'Torque - (lb-ft)',
titlefont=dict( color='rgb(200, 0, 0)' ),
tickfont=dict( color='rgb(200, 0, 0)' ),
range=[0, 120],
showgrid=True,
#zeroline=True,
showline=True,
gridcolor='#bdbdbd',
mirror="ticks",
ticks="inside",
tickwidth=1,
linewidth=2
),
margin={'l': 60, 'b': 40, 't': 30, 'r': 60},
#legend={'x': 0.5, 'y': 1},
hovermode='closest',
showlegend=False,
)
}
if __name__ == '__main__':
app.run_server()

Related

Plotly Dash: How to change image on button click

I had unknowingly added in the answer section of the following thread as I was trying to use that example to complete my usecase:
Plotly: How to display graph after clicking a button?
I am looking for a very similar solution and I tried suggestion 2 (from the above thread), because I want to display images depending upon user's choice of clicking button. I have image_1, image_2, image_3 and image_4 under one directory. I have tried so far like below:
import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import plotly.graph_objs as go
from dash.dependencies import Input, Output
import numpy as np
from plotly.subplots import make_subplots
import plotly.express as px
pd.options.plotting.backend = "plotly"
from datetime import datetime
palette = px.colors.qualitative.Plotly
# sample data
df = pd.DataFrame({'Prices': [1, 10, 7, 5, np.nan, np.nan, np.nan],
'Predicted_prices': [np.nan, np.nan, np.nan, 5, 8, 6, 9]})
# app setup
app = dash.Dash()
# controls
controls = dcc.Card(
[dcc.FormGroup(
[
dcc.Label("Options"),
dcc.RadioItems(id="display_figure",
options=[{'label': 'None', 'value': 'Nope'},
{'label': 'Figure 1', 'value': 'Figure1'},
{'label': 'Figure 2', 'value': 'Figure2'},
{'label': 'Figure 3', 'value': 'Figure3'}
],
value='Nope',
labelStyle={'display': 'inline-block', 'width': '10em', 'line-height': '0.5em'}
)
],
),
dcc.FormGroup(
[dcc.Label(""), ]
),
],
body=True,
style={'font-size': 'large'})
app.layout = dcc.Container(
[
html.H1("Button for predictions"),
html.Hr(),
dcc.Row([
dcc.Col([controls], xs=4),
dcc.Col([
dcc.Row([
dcc.Col(dcc.Graph(id="predictions")),
])
]),
]),
html.Br(),
dcc.Row([
]),
],
fluid=True,
)
#app.callback(
Output("predictions", "figure"),
[Input("display_figure", "value"),
],
)
def make_graph(display_figure):
# main trace
y = 'Prices'
y2 = 'Predicted_prices'
# print(display_figure)
if 'Nope' in display_figure:
fig = go.Figure()
fig.update_layout(plot_bgcolor='rgba(0,0,0,0)', paper_bgcolor='rgba(0,0,0,0)',
yaxis=dict(showgrid=False, zeroline=False, tickfont=dict(color='rgba(0,0,0,0)')),
xaxis=dict(showgrid=False, zeroline=False, tickfont=dict(color='rgba(0,0,0,0)')))
return fig
if 'Figure1' in display_figure:
fig = go.Figure(go.Scatter(name=y, x=df.index, y=df[y], mode='lines'))
fig.add_traces(go.Scatter(name=y, x=df.index, y=df[y2], mode='lines'))
fig.update_layout(template='plotly_dark')
# prediction trace
if 'Figure2' in display_figure:
fig = go.Figure((go.Scatter(name=y, x=df.index, y=df[y], mode='lines')))
fig.add_traces(go.Scatter(name=y, x=df.index, y=df[y2], mode='lines'))
fig.update_layout(template='seaborn')
if 'Figure3' in display_figure:
fig = go.Figure((go.Scatter(name=y, x=df.index, y=df[y], mode='lines')))
fig.add_traces(go.Scatter(name=y, x=df.index, y=df[y2], mode='lines'))
fig.update_layout(template='plotly_white')
# Aesthetics
fig.update_layout(margin={'t': 30, 'b': 0, 'r': 0, 'l': 0, 'pad': 0})
fig.update_layout(hovermode='x')
fig.update_layout(showlegend=True, legend=dict(x=1, y=0.85))
fig.update_layout(uirevision='constant')
fig.update_layout(title="Prices and predictions")
return (fig)
app.run_server(debug=True)
but I got the following error and couldn't proceed further.
line 24, in <module>
controls = dcc.Card(
AttributeError: module 'dash_core_components' has no attribute 'Card'
The problem is that the different components used in your code are defined in different libraries (dash_core_components, dash_html_components and
dash_bootstrap_components), while you are trying to get all the components from the same library (dash_core_components). For instance, dcc.Card should be replaced with dbc.Card where dbc stands for dash_bootstrap_components, see the code below.
import pandas as pd
import numpy as np
import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
from dash.dependencies import Input, Output
import plotly.graph_objs as go
# sample data
df = pd.DataFrame({
'Prices': [1, 10, 7, 5, np.nan, np.nan, np.nan],
'Predicted_prices': [np.nan, np.nan, np.nan, 5, 8, 6, 9]
})
# app setup
app = dash.Dash()
# controls
controls = dbc.Card([
dbc.FormGroup([
html.Label('Options'),
dcc.RadioItems(
id='display_figure',
options=[
{'label': 'None', 'value': 'None'},
{'label': 'Figure 1', 'value': 'Figure1'},
{'label': 'Figure 2', 'value': 'Figure2'},
{'label': 'Figure 3', 'value': 'Figure3'}
],
value='None',
labelStyle={
'display': 'inline-block',
'width': '10em',
'line-height': '0.5em'
}
)
]),
],
body=True,
style={'font-size': 'large'}
)
app.layout = dbc.Container([
html.H1('Button for predictions'),
html.Hr(),
dbc.Row([
dbc.Col([controls], xs=4),
dbc.Col([
dbc.Row([
dbc.Col(dcc.Graph(id='predictions')),
])
]),
]),
],
fluid=True,
)
#app.callback(
Output('predictions', 'figure'),
[Input('display_figure', 'value')],
)
def make_graph(display_figure):
y = 'Prices'
y2 = 'Predicted_prices'
if 'Figure1' in display_figure:
fig = go.Figure(go.Scatter(name=y, x=df.index, y=df[y], mode='lines'))
fig.add_trace(go.Scatter(name=y, x=df.index, y=df[y2], mode='lines'))
fig.update_layout(template='plotly_dark')
fig.update_layout(title='Prices and predictions')
elif 'Figure2' in display_figure:
fig = go.Figure((go.Scatter(name=y, x=df.index, y=df[y], mode='lines')))
fig.add_trace(go.Scatter(name=y, x=df.index, y=df[y2], mode='lines'))
fig.update_layout(template='seaborn')
fig.update_layout(title='Prices and predictions')
elif 'Figure3' in display_figure:
fig = go.Figure((go.Scatter(name=y, x=df.index, y=df[y], mode='lines')))
fig.add_trace(go.Scatter(name=y, x=df.index, y=df[y2], mode='lines'))
fig.update_layout(template='plotly_white')
fig.update_layout(title='Prices and predictions')
else:
fig = go.Figure()
fig.update_layout(
plot_bgcolor='rgba(0,0,0,0)',
paper_bgcolor='rgba(0,0,0,0)',
yaxis=dict(showgrid=False, zeroline=False, tickfont=dict(color='rgba(0,0,0,0)')),
xaxis=dict(showgrid=False, zeroline=False, tickfont=dict(color='rgba(0,0,0,0)'))
)
fig.update_layout(margin={'t': 30, 'b': 0, 'r': 0, 'l': 0, 'pad': 0})
fig.update_layout(hovermode='x')
fig.update_layout(showlegend=True, legend=dict(x=1, y=0.85))
fig.update_layout(uirevision='constant')
return fig
if __name__ == '__main__':
app.run_server(host='127.0.0.1', debug=True)
Once you have fixed this issue, you can update the app to display the static PNG files instead of the interactive graphs as shown below. Note that the dcc.Graph component has been replaced by the html.Img component, and that the figure property has been replaced by the src property.
import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
from dash.dependencies import Input, Output
# app setup
app = dash.Dash()
# controls
controls = dbc.Card([
dbc.FormGroup([
html.Label('Options'),
dcc.RadioItems(
id='display_figure',
options=[
{'label': 'None', 'value': 'None'},
{'label': 'Figure 1', 'value': 'Figure1'},
{'label': 'Figure 2', 'value': 'Figure2'},
{'label': 'Figure 3', 'value': 'Figure3'}
],
value='None',
labelStyle={
'display': 'inline-block',
'width': '10em',
'line-height': '0.5em'
}
)
]),
],
body=True,
style={'font-size': 'large'}
)
app.layout = dbc.Container([
html.H1('Button for predictions'),
html.Hr(),
dbc.Row([
dbc.Col([controls], xs=4),
dbc.Col([
dbc.Row([
dbc.Col(html.Img(id='predictions')),
])
]),
]),
],
fluid=True,
)
#app.callback(
Output('predictions', 'src'),
[Input('display_figure', 'value')],
)
def make_graph(display_figure):
if 'Figure1' in display_figure:
return app.get_asset_url('image_1.png')
elif 'Figure2' in display_figure:
return app.get_asset_url('image_2.png')
elif 'Figure3' in display_figure:
return app.get_asset_url('image_3.png')
else:
return None
if __name__ == '__main__':
app.run_server(host='127.0.0.1', debug=True)
Note also that the PNG files will need to be saved in the assets folder, as shown below:

Plotly Dash: Cannot place figure and table side by side

I am trying to place a figure and a table side-by-side but the table always shows below the figure vertically although its horizontally in the correct position. Similar code works for me if both elements are figures. Here is a minimal code example.
fig = make_subplots()
fig.add_trace(go.Scatter(x = [1,2,3], y = [1,2,3]))
df = pd.DataFrame({'col1': [1, 2, 3], 'col2': ['This is a test ', 'This is a test', 'This is a test'], 'col3': [99, 100, 101]})
app = dash.Dash(__name__)
app.layout = html.Div([
html.Div([dcc.Graph(figure = fig)], style = {'width': '49%', 'display': 'inline-block'}),
html.Div([dt.DataTable(
data=df.to_dict('records'),
columns=[{'id': c, 'name': c} for c in df.columns],
style_table = {'height': 200, 'overflowX': 'auto'})], style = {'width': '49%', 'display': 'inline-block'}),
])
if __name__ == '__main__':
app.run_server(debug = True)
Here is an image of what I get:
Try including the figure and table in a flex container, i.e. an html.Div() with style={'display': 'flex'}.
import pandas as pd
import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_table as dt
import plotly.graph_objects as go
app = dash.Dash(__name__)
app.layout = html.Div([
# Flex container
html.Div([
# Graph container
html.Div([
dcc.Graph(figure=go.Figure(data=go.Scatter(x=[1, 2, 3], y=[1, 2, 3]), layout=dict(margin=dict(t=0, b=0, l=0, r=0))))
], style={'width': '49%', 'display': 'inline-block'}),
# Table container
html.Div([
dt.DataTable(
data=pd.DataFrame({'col1': [1, 2, 3], 'col2': [99, 100, 101]}).to_dict('records'),
columns=[{'id': c, 'name': c} for c in ['col1', 'col2']],
style_table={'height': 200, 'overflowX': 'auto'}
)
], style={'width': '49%', 'display': 'inline-block'}),
], style={'display': 'flex'}),
])
if __name__ == '__main__':
app.run_server(host='127.0.0.1', debug=True)

DASH dropdowns and graph

I am having a problem in updating a map graph based on 3 dropdowns.
I have 3 dropdowns: one for country, one for district and one for category.
When I select 1 dropdown at a time I can see the results on the map.
But what I really want is to zoom in. So when I select country then district, I want to see the results in that particular district only.
Now, if I select a country from the dropdown and then select a category from the other dropdown, I see on the map the results of the whole country. It does not narrow down the search to just the category selected.
dbc.Col([
html.Label("Select Country: ", style={'font-family': 'arial', 'font-weight': 'bold', 'font-size': 15, 'color': 'white'}),
dcc.Dropdown(className='scrollable-element div-for-dropdown Select-control VirtualizedSelectOption',
id='country_dropdown',
options=[{'label': str(c), 'value': c} for c in sorted(df['Country'].unique())],
multi=True,
placeholder="Select",
value=['United Kingdom'],
clearable=True,
style={'width': '100%', 'font-family': 'arial', 'font-weight': 'bold', 'font-size': 13, 'color': 'black', 'background-color': '#31302F', 'border': '0px solid black'}
),
html.Br(),
html.Label("Select District: ", style={'font-family': 'arial', 'font-weight': 'bold', 'font-size': 15, 'color': 'white'}),
dcc.Dropdown(className='scrollable-element div-for-dropdown Select-control VirtualizedSelectOption',
id='district_dropdown',
multi=True,
value=[],
clearable=True,
options=[{'label': str(d), 'value': d} for d in sorted(df['MainLocation'].unique())],
placeholder="Select",
style={'width': '100%', 'font-family': 'arial', 'font-weight': 'bold', 'font-size': 13, 'color': 'black', 'background-color': '#31302F', 'border': '0px solid black'}
),
html.Br(),
html.Label("Select Category: ", style={'font-family': 'arial', 'font-weight': 'bold', 'font-size': 15, 'color': 'white'}),
dcc.Dropdown(className='div-for-dropdown Select-control VirtualizedSelectOption',
id='category_dropdown',
multi=True,
value=[],
clearable=True,
options=[{'label': '(Select All)', 'value': 'all'}] + [{'label': str(cat), 'value': cat} for cat in sorted(df['Category'].unique())],
placeholder="Select",
style={'width': '100%', 'font-family': 'arial', 'font-weight': 'bold', 'font-size': 13, 'color': 'black', 'background-color': '#31302F', 'border': '0px solid black'}
)
`#app.callback(Output('map_graph', 'figure'),
[Input('country_dropdown', 'value'),
Input('category_dropdown', 'value'),
Input('district_dropdown', 'value')])
def update_map_graph(chosen_country, chosen_category, chosen_district):
df_sub = df[(df['Country'].isin(chosen_country)) |
(df['Category'].isin(chosen_category)) |
(df['MainLocation'].isin(chosen_district))]
# Create figure
locations = [go.Scattermapbox(
lon=df_sub['Long'],
lat=df_sub['Lat'],
mode='markers',
marker={'color': df_sub['Color'], 'size': 13, 'opacity': 0.5},
unselected={'marker': {'opacity': 1}},
selected={'marker': {'opacity': 0.5, 'size': 18}},
hoverinfo='text',
hovertext=df_sub['Hover']
)]
# Return figure
return {
'data': locations,
'layout': go.Layout(
autosize=True,
margin=dict(l=0,
r=0,
t=0,
b=0),
uirevision='foo',
clickmode='event+select',
hovermode='closest',
hoverdistance=2,
mapbox=dict(
accesstoken=mapbox_access_token,
bearing=0,
style='mapbox://styles/mapbox/navigation-night-v1',
center=dict(
lat=50.1109,
lon=8.6821
),
pitch=0,
zoom=5
),
)
}`
you don't provide sample data, so I've used UK hospital data
create a geopandas data frame, so total_bounds can be used
straight forward build drop downs progressively. get centre of geometry of any selections
import json
import numpy as np
import dash
import plotly.graph_objects as go
from dash.dependencies import Input, Output, State
from jupyter_dash import JupyterDash
import requests, io
import pandas as pd
import geopandas as gpd
import shapely
import plotly.express as px
# get some public addressess - hospitals. data that can be scattered
dfhos = pd.read_csv(
io.StringIO(
requests.get("http://media.nhschoices.nhs.uk/data/foi/Hospital.csv").text
),
sep="¬",
engine="python",
)
fig = px.scatter_mapbox(
dfhos, lat="Latitude", lon="Longitude", hover_data=["County", "City", "Address1"]
).update_layout(
mapbox={"style": "carto-positron"}, margin={"l": 0, "r": 0, "t": 0, "b": 0}
)
# create a geo dataframe of hospitals
gdfhos = gpd.GeoDataFrame(
data=dfhos,
geometry=dfhos.apply(
lambda r: shapely.geometry.Point(r["Longitude"], r["Latitude"]), axis=1
),
crs="EPSG:4326",
)
# Build App
app = JupyterDash(__name__)
app.layout = dash.html.Div(
[
dash.dcc.Dropdown(
id="County",
options=[
{"label": c, "value": c}
for c in dfhos["County"].dropna().sort_values().unique()
],
value=None,
),
dash.dcc.Dropdown(id="City", value=None),
dash.dcc.Dropdown(id="Address1", value=None),
dash.dcc.Graph(
id="map",
figure=fig,
),
],
)
#app.callback(
[
Output("map", "figure"),
Output("City", "options"),
Output("Address1", "options"),
],
Input("County", "value"),
Input("City", "value"),
Input("Address1", "value"),
State("map", "figure"),
)
def center_selection(county, city, address1, fig):
city_out = []
addr_out = []
bb = gdfhos.geometry.total_bounds
if county:
bb = gdfhos.loc[gdfhos["County"].eq(county)].geometry.total_bounds
city_out = [
{"label": c, "value": c}
for c in dfhos.loc[dfhos["County"].eq(county), "City"]
.dropna()
.sort_values()
.unique()
]
if county and city:
bb = gdfhos.loc[
gdfhos["County"].eq(county) & gdfhos["City"].eq(city)
].geometry.total_bounds
addr_out = [
{"label": c, "value": c}
for c in dfhos.loc[
dfhos["County"].eq(county) & dfhos["City"].eq(city), "OrganisationName"
]
.dropna()
.sort_values()
.unique()
]
return (
go.Figure(fig).update_layout(
mapbox={"center": {"lon": (bb[0] + bb[2]) / 2, "lat": (bb[1] + bb[3]) / 2}}
),
city_out,
addr_out,
)
# Run app and display result inline in the notebook
app.run_server(mode="inline")

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