Related
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:
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.
This maybe asking alot, but I was curious if anyone had any tips for combining these two dash scripts. The purpose would be to incorporate the drop down menu to remove/add data points on the visualization plots.
The first script will visualize my data nicely and the second script with the callback function is for creating a drop down menu from the plotly tutorials.
import dash
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('boilerData.csv', index_col='Date', parse_dates=True)
df = df.fillna(method = 'ffill').fillna(method = 'bfill')
app.layout = html.Div([
dcc.Graph(
id='hws',
figure={
'data': [
{'x': df.index, 'y': df.HWST, 'type': 'line', 'name': 'hwst'},
{'x': df.index, 'y': df.HWRT, 'type': 'line', 'name': 'hwrt'},
{'x': df.index, 'y': df.OAT, 'type': 'line', 'name': 'oat'},
],
'layout': {
'title': 'Heating System Data Visualization'
}
}
)
])
if __name__ == '__main__':
app.run_server(debug=True)
dropdown script:
import dash
import dash_html_components as html
import dash_core_components as dcc
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.layout = html.Div([
dcc.Dropdown(
id='my-dropdown',
options=[
{'label': 'Outdoor Temp', 'value': 'OAT'},
{'label': 'Hot Water Supply Temp', 'value': 'HWST'},
{'label': 'Hot Water Return Temp', 'value': 'HWRT'}
],
value=['OAT','HWST','HWRT'],
multi=True
),
html.Div(id='output-container')
])
#app.callback(
dash.dependencies.Output('output-container', 'children'),
[dash.dependencies.Input('my-dropdown', 'value')])
def update_output(value):
return 'You have selected "{}"'.format(value)
if __name__ == '__main__':
app.run_server(debug=True)
Any tips help, still learning...
What you need to know is that the callback takes Input from some Dash element (here the value of the dropdown) and returns to Output for some property of another Dash element (here the figure from the graph; notice we only change the data property).
import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import plotly.graph_objs as go
import numpy as np
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
df = pd.read_csv('boilerData.csv', index_col='Date', parse_dates=True)
df = df.fillna(method = 'ffill').fillna(method = 'bfill')
app.layout = html.Div([
dcc.Dropdown(
id='my-dropdown',
options=[
{'label': 'Outdoor Temp', 'value': 'OAT'},
{'label': 'Hot Water Supply Temp', 'value': 'HWST'},
{'label': 'Hot Water Return Temp', 'value': 'HWRT'}
],
value=['OAT','HWST','HWRT'],
multi=True
),
dcc.Graph(
id='hws',
figure={
'data': [
{'x': df.index, 'y': df.HWST, 'type': 'line', 'name': 'hwst'},
{'x': df.index, 'y': df.HWRT, 'type': 'line', 'name': 'hwrt'},
{'x': df.index, 'y': df.OAT, 'type': 'line', 'name': 'oat'},
],
'layout': {
'title': 'Heating System Data Visualization'
}
}
)
])
#app.callback(
dash.dependencies.Output('hws', 'figure'),
[dash.dependencies.Input('my-dropdown', 'value')])
def update_output(columns):
return {"data": [{'x': df.index, 'y': df[col], 'type':'line', 'name': col}
for col in columns]}
if __name__ == '__main__':
app.run_server(debug=True)
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
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()