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)
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:
[Error while connecting to 127.0.0.1[\]\[1\][1]
[1]: https://i.stack.imgur.com/qo2mY.png
My code is like this :-
import dash
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html
from pandas_datareader import data as web
from datetime import datetime as dt
app = dash.Dash('Hello World')
app.layout = html.Div([
dcc.Dropdown(
id='my-dropdown',
options=[
{'label': 'Coke', 'value': 'COKE'},
{'label': 'Tesla', 'value': 'TSLA'},
{'label': 'Apple', 'value': 'AAPL'}
],
value='COKE'
),
dcc.Graph(id='my-graph')
], style={'width': '500'})
#app.callback(Output('my-graph', 'figure'), [Input('my-dropdown', 'value')])
def update_graph(selected_dropdown_value):
df = web.DataReader(
selected_dropdown_value,
'google',
dt(2017, 1, 1),
dt.now()
)
return {
'data': [{
'x': df.index,
'y': df.Close
}],
'layout': {'margin': {'l': 40, 'r': 0, 't': 20, 'b': 30}}
}
app.css.append_css({'external_url': 'https://codepen.io/chriddyp/pen/bWLwgP.css'})
if __name__ == '__main__':
app.run_server(host='127.0.0.1',port = 8050,debug=True)
---------------------------------------------------------------------------------------------------------My question when I try to put http://127.0.0.1:8050 it says 127.0.0.1 refused to connect.Mine is windows 10 OS.I tried IIS services but still I dont know how to use that.Please help me with the error.
Thanks.
I am new to python and trying to create dashboard and i want the graph to view side by side instead of one below another.
app = dash.Dash()
app.layout = html.Div(children=[
html.H1('Premium Dash Board'),
html.Div(children='Premium Queue'),
html.Div([
dcc.Graph(id='example',
figure={
'data':[
{'x': ASIN, 'y': Quan, 'type': 'bar', 'name': 'Quantity'},
{'x': ASIN, 'y':List_price, 'type': 'bar', 'name': 'Price'}
],
'layout': {
'title': 'ASIN vs Inventory & Price'
}
}),
],style={'display': 'inline-block'}),
html.Div([
dcc.Graph(id='example1',
figure={
'data': [
{'x': ASIN, 'y': Quan, 'type': 'line', 'name': 'Quantity'},
{'x': ASIN, 'y': List_price, 'type': 'line', 'name': 'Price'}
],
'layout': {
'title': 'ASIN vs Inventory & Price'
}
})
], style={'display': 'inline-block'})
],style={'width': '100%', 'display': 'inline-block'})
Please advise how to proceed.
If I run code on big monitor then I see plots side by side.
If I use smaller window then it automatically put second plot below.
But using 'width': '50%' I can get two plots side by side
import dash
import dash_html_components as html
import dash_core_components as dcc
import random
random.seed(0)
ASIN = list(range(100))
Quan = [random.randint(0, 100) for x in range(100)]
List_price = [random.randint(0, 100) for x in range(100)]
app = dash.Dash()
app.layout = html.Div(children=[
html.H1('Premium Dash Board'),
html.Div(children='Premium Queue'),
html.Div([
dcc.Graph(id='example',
figure={
'data':[
{'x': ASIN, 'y': Quan, 'type': 'bar', 'name': 'Quantity'},
{'x': ASIN, 'y': List_price, 'type': 'bar', 'name': 'Price'}
],
'layout': {
'title': 'ASIN vs Inventory & Price'
}
}),
],style={'width': '50%','display': 'inline-block'}),
html.Div([
dcc.Graph(id='example1',
figure={
'data': [
{'x': ASIN, 'y': Quan, 'type': 'bar', 'name': 'Quantity'},
{'x': ASIN, 'y': List_price, 'type': 'bar', 'name': 'Price'}
],
'layout': {
'title': 'ASIN vs Inventory & Price'
}
})
],style={'width': '50%','display': 'inline-block'}),
])
app.run_server()
TO create this image I used DevTools in Firefox and function to test page with devices which have different screen size - Ctrl+Shift+M
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.
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