A single datepicker for multiple dash tables - python

I would like to select dates in several tables, using dash_table . This works when using a different date picker for each table, but not when using a single date picker for all separate tables.
A simple reproducible example shows a single table, and data can be selected and displayed for different dates (here 1st, 2nd, or 3rd January).
My question: how to make three tables, – one for each country -, using a single date picker (not three). Thank you very much in advance for any suggestions!
Modules
import pandas as pd
import plotly.graph_objs as go
import dash
import dash_table
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State, Event
import datetime
from datetime import datetime as dt
Fictive DataFrame
df = pd.DataFrame({'dd':['2019-01-01', '2019-01-01', '2019-01-01', '2019-01-02', '2019-01-02', '2019-01-02', '2019-01-03', '2019-01-03'], 'country':['Belgium', 'Belgium','France', 'France', 'Belgium', 'France', 'Belgium', 'Germany'], 'value':[10,20,30,10,15,25,5,70]})
Script
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.config['suppress_callback_exceptions']=True
currentday = 1
currentmonth = 1
currentyear = 2019
app.layout = html.Div(
[
html.H4('All countries'),
dcc.DatePickerSingle(
id='my-date-picker-single1',
min_date_allowed=dt(2012, 1, 1),
max_date_allowed=dt(2019, 2, 25),
initial_visible_month=dt(currentyear, currentmonth, currentday),
date=dt(currentyear, currentmonth, currentday),
disabled=False
),
dcc.Store(id="selected-rows1", storage_type="memory"),
html.Div(id="tables-container1"),
dash_table.DataTable(
id="table1",
columns=[{"name": i, "id": i} for i in ['dd', 'country', 'value'] ],
style_cell_conditional=[
{
'if':{'filter':'Country eq "France"'},
'backgroundColor':'rgb(150, 150, 150)'
}
] + [
{'if': {'column_id': c},
'textAlign': 'left'
} for c in ['dd', 'country']
],
sorting=True,
sorting_type='multi',
sorting_settings=[],
)
]
)
#app.callback(
Output("selected-rows1", "data"),
[Input("my-date-picker-single1", "date")],
[State("selected-rows1", "data")],
)
def display_output(value, storage):
if value is not None:
return {"selected_rows1": df[df["dd"].str.contains(value)].to_json()}
#app.callback(
Output("table1", "data"),
[Input("table1", "sorting_settings"), Input("selected-rows1", "data")],
)
def update_graph(sorting_settings, rows):
_df = pd.read_json(rows["selected_rows1"])
if sorting_settings is not None and len(sorting_settings):
for setting in sorting_settings:
_df.sort_values(
by=setting["column_id"],
ascending=(setting["direction"] == "asc"),
inplace=True,
)
return _df.to_dict("rows")
else:
return _df.to_dict("rows")
if __name__ == "__main__":
app.run_server(debug=True)
Your advice is highly appreciated!

You should use multiple callbacks. Check section on "Multiple Outputs". Example:
#app.callback(
Output("selected-rows1", "data"),
[Input("my-date-picker-single1", "date")],
[State("selected-rows1", "data")])
def display_output_1(value, storage):
if value is not None:
return {"selected_rows1": df[df["dd"].str.contains(value)].to_json()}
#app.callback(
Output("selected-rows2", "data"),
[Input("my-date-picker-single1", "date")],
[State("selected-rows2", "data")])
def display_output_2(value, storage):
if value is not None:
return {"selected_rows2": df[df["dd"].str.contains(value)].to_json()}

Related

Plotly Callbacks Dynamic Table

Hi I'm trying to understand how I can do this using only one data source or data frame in pandas python. (Plotly)
Let's say that I have a dataframe that is compiled of sample sales data:
e.g.
date (month) | client name | sales rep name | total_sales
YYYY-M Jane Doe Adam float
My sample layout has a chained callback that displays and organizes:
Dropdown1: Sales Rep Name
Dropdown2: Client Names (These Clients are unique to the selected Sales Rep Name)
Graph of x= Date, y = Sales ^^^ determined by these selected
I want to make a month over month table or even a visual (line graph) that generates based on the selected at the top but how would I go about it?
Is there a built in function for Month Over Month growth?
Please help in steps this is greatly appreciated.
import dash
from dash import dcc as dcc
from dash import html as html
from dash.dependencies import Input, Output
import pandas as pd
import plotly.express as px
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
df = pd.read_csv(r"C:\Users\rbricker\Desktop\sales.csv")
app.layout = html.Div([
html.Label("Sales Rep Names:", style={'fontSize': 30, 'textAlign': 'center'}),
dcc.Dropdown(
id='sales-rep',
options=[{'label': s, 'value': s} for s in sorted(df.SalesRepName.unique())],
value='Adam',
clearable=False
),
html.Label("Clients", style={'fontSize': 30, 'textAlign': 'center'}),
dcc.Dropdown(id='client-name', options=[], multi=True),
dcc.Graph(id='display-chart', figure={})
])
#app.callback(
Output('client-name', 'options'),
Input('sales-rep', 'value')
)
def set_client_options(chosen_sales_rep):
dff = df[df.SalesRepName == chosen_sales_rep]
return [{'label': c, 'value': c} for c in sorted(dff.Clients.unique())]
#app.callback(
Output(client-name', 'value'),
Input('client-name', 'options')
)
def set_client_name_value(available_options):
return [x['value'] for x in available_options]
#app.callback(
Output('display-chart', 'figure'),
Input('client-name', 'value'),
Input('sales-rep', 'value')
)
def update_graph(selected_client_name, selected_sales_rep):
if len(selected_client_name) == 0:
return dash.no_update
else:
dff = df[(df.SalesRepName == selected_sales_rep) & (df.Clients.isin(selected_client_name))]
fig = px.line(dff, x='DatePeriod', y='total',
color='Clients',
hover_name='Clients')
return fig
if __name__ == '__main__':
app.run_server(debug=True)

Update dashtable columns name dynamically

I'm trying to make a dashtable and its columns will be change dynamically based on dropdowns value.
Below is my sample code:
import pandas as pd
import numpy as np
import plotly.express as px
import dash
from dash import html
from dash import dcc
from dash.dependencies import Input, Output,State
import dash_bootstrap_components as dbc
import plotly.graph_objects as go
from dash import dash_table
df1 = pd.DataFrame({
'Contract No': ['VN122001','VN122002','VN122003','VN122004','VN122005'],
'Amount': [22071,20775,20841,21891,22395]})
df1 = df1.set_index('Contract No')
df2 = pd.DataFrame({
'Contract No': ['VN122001','VN122002','VN122003','VN122004','VN122005'],
'Cusname': ['A','B','C','D','E'],
'Branch': ['HN','HCM','HP','BN','DN']})
df2 = df2.set_index('Contract No')
app = dash.Dash(__name__,external_stylesheets=[dbc.themes.LUX])
app.layout = html.Div([
dbc.Row([
dbc.Col([
dcc.Dropdown(id='columns_name',placeholder="Columns name", # Dropdown for heatmap color
options=list_column,
value='Cusname',
multi=False,
disabled=False,
clearable=True,
searchable=True)
],width={'size':4,'offset':0,'order':1},style={'padding-top' : 15}),
]),
dbc.Row([
html.Div(
id = 'tableDiv',
className = 'tableDiv'
)
])
])
#app.callback(Output('tableDiv', 'children'),
[Input('columns_name', 'value')])
def update_columns_name(columns):
col_name = df2[[columns]]
df3 = pd.merge(df1, col_name, left_index=True, right_index=True)
df3 = df3.reset_index()
mycolumns = [{'name': i, 'id': i} for i in df3.columns]
return html.Div([
dash_table.DataTable(
id='table',
columns=mycolumns,
data=df3.to_dict("rows")
)
])
if __name__ == "__main__":
app.run_server(debug=False,port=1222)
Actually it is working well but when I try to create Tabs and then return it to Tab, nothing show. Below is my code to create Tab.
app.layout = html.Div([dbc.Tabs(
[dbc.Tab(label="Dashboard", tab_id="dashboard"),
dbc.Tab(label="Table", tab_id="table"),
],
id="tabs",
active_tab="dashboard"),
html.Div(id="tab-content", className="p-4"),
])
#app.callback(
Output("tab-content", "children"),
[Input("tabs", "active_tab")])
def render_tab_content(active_tab):
if active_tab == "dashboard":
return html.Div([dbc.Row([html.H5('Graphs')])])
elif active_tab == "table":
return html.Div([
dbc.Row([
html.Div(id = 'tableDiv',
className = 'tableDiv')
])
])
#app.callback(Output('tableDiv', 'children'),
[Input('columns_name', 'value')])
def update_columns_name(columns):
col_name = df2[[columns]]
df3 = pd.merge(df1, col_name, left_index=True, right_index=True)
df3 = df3.reset_index()
mycolumns = [{'name': i, 'id': i} for i in df3.columns]
return html.Div([
dash_table.DataTable(
id='table',
columns=mycolumns,
data=df3.to_dict("rows"))
])
if __name__ == "__main__":
app.run_server(debug=False,port=1222)
What should I do to fix this issue. Thank you.
This is the error javascript throws back in the browser console:
Object { message: "ID not found in layout", html: "Attempting to connect a callback Output item to component:\n \"tableDiv\"\nbut no components with that id exist in the layout.\n\nIf you are assigning callbacks to components that are\ngenerated by other callbacks (and therefore not in the\ninitial layout), you can suppress this exception by setting\n```suppress_callback_exceptions=True```.\nThis ID was used in the callback(s) for Output(s):\n tableDiv.children" } dash_renderer.v2_1_0m1644023699.min.js:2:84904
Object { message: "ID not found in layout", html: "Attempting to connect a callback Input item to component:\n \"columns_name\"\nbut no components with that id exist in the layout.\n\nIf you are assigning callbacks to components that are\ngenerated by other callbacks (and therefore not in the\ninitial layout), you can suppress this exception by setting\n```suppress_callback_exceptions=True```.\nThis ID was used in the callback(s) for Output(s):\n tableDiv.children" }
As it suggests, you are referring to id components that are generated by another callback (namely, callback render_tab_content generates the tableDiv div and is being referred to by update_column_name). This is a problem, as your tableDiv won't be present when you select the dashboard table but the callback may still be invoked (at least initially which is why you are having an issue to begin with).
It's best to perhaps have the contents of update_column_name combined with render_table_content and generate the column stuff you need through the one callback. You don't really gain anything from splitting into 2 callbacks in this instance, and if you really want, you can abstract the contents of the other callback into a normal function and just call it in render_tab_content. Here is a suggested adaptation:
def update_columns_name(columns):
col_name = df2[[columns]]
df3 = pd.merge(df1, col_name, left_index=True, right_index=True)
df3 = df3.reset_index()
mycolumns = [{'name': i, 'id': i} for i in df3.columns]
return (
html.Div([
dbc.Row([
html.Div([
html.Div([
dash_table.DataTable(
id='table',
columns=mycolumns,
data=df3.to_dict("rows")
)
])
],
id='tableDiv',
className='tableDiv')
])
])
)
#app.callback(
Output("tab-content", "children"),
[Input("tabs", "active_tab")],
[State('columns_name', 'value')]
)
def render_tab_content(active_tab, columns):
print(active_tab, columns)
if active_tab == "dashboard":
return html.Div([dbc.Row([html.H5('Graphs')])])
elif active_tab == "table":
return update_columns_name(columns)

multiple chained callbacks in plotly (date range picker)

I have a dictionary, which contains of 3 dataframes (columns are identical), two dropdowns and one date range picker. First dropdown to choose the dataframe, the second to choose the columns. I have implemented 2 chained callbacks for dropdowns and now I want to create a third chained DatePickerRange which gives the Date through DatePickerRange. So in steps, first we select the dataframe, the filtered list of columns appears for that dataframe and as a next step, I want the DatePickerRange to get updated with the min and max Date values of that dataframes' column (date).
I tried to do something on my own but it doesn't work, my major doubts are I can't find a way to fill in start_date, end_date and I do need a third #app.callback but I don't know how to further do that. Thank you in advance. Here's the code:
import pandas as pd
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objects as go
from dash.dependencies import Input, Output, State
import urllib.request
import dash
import datetime as dt
import pandas as pd
from dash.dependencies import Input, Output, State, ClientsideFunction
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
import plotly
import plotly.express as px
import pandas as pd
import requests
from datetime import datetime
import plotly.graph_objects as go
df1 = {'date': ['2021-07-17 04:00:03', '2021-07-18 06:02:25', '2021-07-18 06:02:25'], 'prices': [31370, 35370, 32370]}
df1 = pd.DataFrame(data=df1)
df2 = {'date': ['2021-07-17 04:10:03', '2021-07-18 06:27:25', '2021-07-18 09:02:25'], 'prices': [1370, 8370, 2370]}
df2 = pd.DataFrame(data=df2)
df3 = {'date': ['2021-07-18 05:10:08', '2021-07-19 06:27:25', '2021-07-19 09:02:25'], 'prices': [24, 58, 123]}
df3 = pd.DataFrame(data=df3)
dict_main = {'df1': df1, 'df2': df2, 'df3': df3}
#----------------------------------------------------------------------
app = dash.Dash(__name__)
server = app.server
rpm = list(dict_main.keys())
channels = dict_main[rpm[0]]
for speed in rpm:
start_date = dict_main[speed]['date'][0]
end_date = dict_main[speed]['date'].to_list()[-1]
for speed in rpm:
start_date = dict_main[speed]['date'][0]
end_date = dict_main[speed]['date'].to_list()[-1]
app.layout = html.Div(
[
html.Div([
dcc.Dropdown(
id='rpm-dropdown',
options=[{'label':speed, 'value':speed} for speed in rpm],
value=list(dict_main.keys())[0],
searchable=True
),
],style={'width': '20%', 'display': 'inline-block'}),
html.Div([
dcc.Dropdown(
id='channel-dropdown',
multi=True,
),
],style={'width': '20%', 'display': 'inline-block'}
),
html.Div([
dcc.DatePickerRange(
id = 'daterange',
start_date = start_date,
end_date = end_date
),
], style={'width': '98%', 'display': 'inline-block'}
),
html.Div([
dcc.Graph(
id='Main-Graph'
),
], style={'width': '98%', 'display': 'inline-block'}
)
]
)
#app.callback(
Output('channel-dropdown', 'options'),
[Input('rpm-dropdown', 'value')])
def update_date_dropdown(speed):
return [{'label': i, 'value': i} for i in dict_main[speed].drop(columns = 'date')]
#app.callback(
Output('Main-Graph', 'figure'),
[Input('channel-dropdown', 'value')],
[State('rpm-dropdown', 'value'),
State('daterange', 'start_date'),
State('daterange', 'end_date')])
def updateGraph(channels, test, start_date, end_date):
for speed in rpm:
dff = dict_main[speed]
dff = dff[(dff['date'] > dict_main[speed]['date'][0]) & (dff['date'] < dict_main[speed]['date'].to_list()[-1])]
if channels:
return go.Figure(data=[go.Scatter(x=dict_main[test]['date'], y=dict_main[test][i], name=i) for i in channels])
else:
return go.Figure(data=[])
if __name__ == '__main__':
app.run_server(port =8050)

keyerror 'column name' updating plotly dash figure

Issue:
I'm trying to load a simple plotly scatter plot, where
x axis = keyword
y axis = date
color = locale
however, even plotly throws a key error every time I add the "color" variable. The error code I get states that I don't have a column by that name, but when I print the column names I see the column there.
Anyone faced a similar issue?
Data:
Code:
# Importing needed libraries
import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
import dash_table
from dash.dependencies import Input, Output
import plotly.express as px
import pandas as pd
import random
import datetime
import plotly.graph_objects as go
# Reading the dataframe
df = pd.read_csv('./beanstalk_app/ti_data_ti_dash_v1.csv')
categories = df['category']
locales = df['locale']
# clean dataframe
ti_data = df.copy()
ti_data = ti_data.sample(1000)
# Contents of the app
# 1.Controls
# 1.1 Dropdown list
locs = dcc.Dropdown(id='choose_loc',
options=[
{
'label': locale, 'value': locale
} for locale in locales.unique()
],
placeholder='Select Locale')
cats = dcc.Dropdown(id='choose_cat',
options=[
{
'label': c, 'value': c
} for c in categories.unique()
],
placeholder='Select Category')
# 1.2 DatePicker
datepick = dcc.DatePickerRange(
id='choose_date',
min_date_allowed=df.date.min(),
max_date_allowed=df.date.max(),
initial_visible_month=df.date.min(),
clearable=True,
start_date=df.date.min(),
end_date=df.date.max()
)
# 2.Interactive table
table = dash_table.DataTable(
id='datatable',
columns=[
{"name": i, "id": i, "selectable": True, "presentation": "markdown"}
if i == "google_query"
else {"name": i, "id": i, "selectable": True}
for i in df.columns
],
data=df.to_dict('records'),
editable=False,
filter_action="native",
sort_action="native",
sort_mode="multi",
column_selectable="single",
row_selectable="multi",
row_deletable=True,
selected_columns=[],
selected_rows=[],
page_action="native",
page_current=0,
page_size=10,
style_cell={
'whiteSpace': 'normal',
'height': 'auto',
},
)
# Initialize the app
app = dash.Dash(__name__)
app.title = 'Dot Graph Demo - All Entities'
app.layout = html.Div([
# modifiable table
dbc.Container([
dbc.Row(
[
dbc.Col(locs, width=4),
dbc.Col(cats, width=4),
dbc.Col(datepick, width=4)
]
),
dbc.Row(
table
),
], style={'backgroundColor': '#faf9f9'}),
# graphs resulting from modified table
html.Div(dcc.Graph(id='key_graph_l'))
],
style={'backgroundColor': '#faf9f9'})
# add callback functions
#app.callback(
Output('datatable', 'data'),
[
Input('choose_cat', 'value'),
Input('choose_loc', 'value'),
Input('choose_date', 'start_date'),
Input('choose_date', 'end_date')
]
)
def update_table(choose_cat, choose_loc, start_date, end_date):
df = ti_data.copy()
df['date'] = pd.to_datetime(df['date'])
df['date'] = df['date'].dt.date
if choose_cat is not None:
df = df[df['category'] == choose_cat]
if choose_loc is not None:
df = df[df['locale'] == choose_loc]
if start_date is not None and end_date is not None:
start_date = datetime.datetime.strptime(start_date, "%Y-%m-%d").date()
end_date = datetime.datetime.strptime(end_date, "%Y-%m-%d").date()
df = df.loc[(df.date >= start_date) & (df.date <= end_date)]
data = df.to_dict('records')
return data
#app.callback(
Output('datatable', 'style_data_conditional'),
Input('datatable', 'selected_columns')
)
def update_styles(selected_columns):
return [{
'if': {'column_id': column},
'background_color': '#D2F3FF'
} for column in selected_columns]
#app.callback(
Output('key_graph_l', 'figure'),
[
Input('choose_date', 'start_date'),
Input('choose_date', 'end_date'),
Input('choose_cat', 'value'),
Input('choose_loc', 'value')
]
)
def update_key_l(choose_loc, choose_cat, start_date, end_date):
df = ti_data.copy()
if choose_cat is not None:
df = df[df['category'] == choose_cat]
if choose_loc is not None:
df = df[df['locale'] == choose_loc]
if start_date is not None and end_date is not None:
df = df.loc[(df.date >= start_date) & (df.date <= end_date)]
df = df.sort_values('total_count', ascending=False)[:25]
figure = px.scatter(df, x='keyword', y='date', color='locale', size='total_count',labels={'keyword': 'Keyword', 'total_count': 'Total Count', 'locale': 'Locale', 'date': 'Date'},
title='Weighing top words accross locales')
return figure
# requirements for beanstalk (aws)
if __name__ == '__main__':
app.run_server(debug=True)
The reason for the error is that the order of the arguments in the callback function is different. The error occurs because the date format that is set when there is no calendar selection does not match the date format handled in Dash.
# Importing needed libraries
import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
import dash_table
from dash.dependencies import Input, Output
import plotly.express as px
import pandas as pd
import random
import datetime
import plotly.graph_objects as go
from jupyter_dash import JupyterDash
# Reading the dataframe
df = pd.read_csv('./beanstalk_app/ti_data_ti_dash_v1.csv')
categories = df['category']
locales = df['locale']
# clean dataframe
ti_data = df.copy()
ti_data = ti_data.sample(4) # sample data
# Contents of the app
# 1.Controls
# 1.1 Dropdown list
locs = dcc.Dropdown(id='choose_loc',
options=[
{
'label': locale, 'value': locale
} for locale in locales.unique()
],
placeholder='Select Locale')
cats = dcc.Dropdown(id='choose_cat',
options=[
{
'label': c, 'value': c
} for c in categories.unique()
],
placeholder='Select Category')
# 1.2 DatePicker
datepick = dcc.DatePickerRange(
id='choose_date',
min_date_allowed=df.date.min(),
max_date_allowed=df.date.max(),
initial_visible_month=df.date.min(),
clearable=True,
start_date=df.date.min(),
end_date=df.date.max()
)
# 2.Interactive table
table = dash_table.DataTable(
id='datatable',
columns=[
{"name": i, "id": i, "selectable": True, "presentation": "markdown"}
if i == "google_query"
else {"name": i, "id": i, "selectable": True}
for i in df.columns
],
data=df.to_dict('records'),
editable=False,
filter_action="native",
sort_action="native",
sort_mode="multi",
column_selectable="single",
row_selectable="multi",
row_deletable=True,
selected_columns=[],
selected_rows=[],
page_action="native",
page_current=0,
page_size=10,
style_cell={
'whiteSpace': 'normal',
'height': 'auto',
},
)
# Initialize the app
app = dash.Dash(__name__)
app.title = 'Dot Graph Demo - All Entities'
app.layout = html.Div([
# modifiable table
dbc.Container([
dbc.Row(
[
dbc.Col(locs, width=4),
dbc.Col(cats, width=4),
dbc.Col(datepick, width=4)
]
),
dbc.Row(
table
),
], style={'backgroundColor': '#faf9f9'}),
# graphs resulting from modified table
html.Div(dcc.Graph(id='key_graph_l'))
],
style={'backgroundColor': '#faf9f9'})
# add callback functions
#app.callback(
Output('datatable', 'data'),
[
Input('choose_cat', 'value'),
Input('choose_loc', 'value'),
Input('choose_date', 'start_date'),
Input('choose_date', 'end_date')
]
)
def update_table(choose_cat, choose_loc, start_date, end_date):
df = ti_data.copy()
# df['date'] = pd.to_datetime(df['date'])
# df['date'] = df['date'].dt.date
if choose_cat is not None:
df = df[df['category'] == choose_cat]
if choose_loc is not None:
df = df[df['locale'] == choose_loc]
if start_date is not None and end_date is not None:
# start_date = datetime.datetime.strptime(start_date, "%Y-%m-%dT00:00:00").date()
# end_date = datetime.datetime.strptime(end_date, "%Y-%m-%dT00:00:00").date()
df = df.loc[(df.date >= start_date) & (df.date <= end_date)]
data = df.to_dict('records')
return data
#app.callback(
Output('datatable', 'style_data_conditional'),
Input('datatable', 'selected_columns')
)
def update_styles(selected_columns):
return [{
'if': {'column_id': column},
'background_color': '#D2F3FF'
} for column in selected_columns]
#app.callback(
Output('key_graph_l', 'figure'),
[
Input('choose_cat', 'value'),
Input('choose_loc', 'value'),
Input('choose_date', 'start_date'),
Input('choose_date', 'end_date')
]
)
def update_key_l(choose_cat, choose_loc, start_date, end_date):
df = ti_data.copy()
if choose_cat is not None:
df = df[df['category'] == choose_cat]
if choose_loc is not None:
df = df[df['locale'] == choose_loc]
if start_date is not None and end_date is not None:
df = df.loc[(df.date >= start_date) & (df.date <= end_date)]
df = df.sort_values('total_count', ascending=False)[:25]
figure = px.scatter(df, x='keyword', y='date', color='locale', size='total_count',labels={'keyword': 'Keyword', 'total_count': 'Total Count', 'locale': 'Locale', 'date': 'Date'},
title='Weighing top words accross locales')
return figure
# requirements for beanstalk (aws)
if __name__ == '__main__':
app.run_server(debug=True)

Graph_Update with two dropdown with multiple selection using excel data and dash python

I am trying to update a graph in dash using an excel with data. I have 2 drop down and an excel document with different sheets for each drop down. I couldn't manage yet to select a value from drop down and to charge that data into the table (I have also a table before the graph) and plot values into the graph.
import dash
import dash_auth
import dash_core_components as dcc
import dash_html_components as html
import plotly
import dash_daq as daq
import os
import random
import pandas as pd
import plotly.graph_objs as go
from collections import deque
import psycopg2
from dash.dependencies import Output, Input
DB_NAME = "LicentaTest"
DB_USER = "postgres"
DB_PASS = "admin"
DB_HOST = "localhost"
DB_PORT = "5433"
VALID_USERNAME_PASSWORD_PAIRS = [
['admin1', 'admin']
]
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(_name_, external_stylesheets=external_stylesheets)
auth = dash_auth.BasicAuth(
app,
VALID_USERNAME_PASSWORD_PAIRS
)
df = pd.read_excel('UploadData.xlsx', sheet_name='Total')
def generate_table(dataframe, max_rows=13):
return html.Table(
# Header
[html.Tr([html.Th(col) for col in dataframe.columns])] +
# Body
[html.Tr([
html.Td(dataframe.iloc[i][col]) for col in dataframe.columns
]) for i in range(min(len(dataframe), max_rows))]
)
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(_name_, external_stylesheets=external_stylesheets)
app.layout = html.Div([
html.H1('Electrica SDEE Transilvania SUD SA'),
html.H4('Select the branch:'),
dcc.Dropdown(
id='dropdown',
options=[{'label': i, 'value': i} for i in ['ALBA', 'BRASOV',
'COVASNA', 'HARGHITA', 'MURES', 'SIBIU', 'TOTAL']],
value='',
placeholder = 'Select branch'
#multi = True
),
html.H4('Select the year:'),
dcc.Dropdown(
id='dropdown1',
options=[{'label': i, 'value': i} for i in ['2012', '2013',
'2014', '2015', '2016', '2017', '2018', 'ALL']],
value='',
placeholder = 'Select year'
),
html.Br(),
html.Button('OK', id='submit-form'),
html.Br(),
html.Div(children=[
html.H4(children='Own Technological Consumption'),
generate_table(df),
]),
html.Br(),
html.Br(),
html.Br(),
dcc.Graph(id='graph')],
className='container')
#app.callback(
dash.dependencies.Output('graph', 'figure'),
[dash.dependencies.Input('dropdown', 'value')])
def update_graph1(dropdown_value):
df = pd.read_excel('UploadData.xlsx', sheet_name='Total')
X1 = df.Date.values
Y1 = df.CPT.values
data = plotly.graph_objs.Scatter(
x=X1,
y=Y1,
name='Graph',
mode='lines+markers'
)
return {
'data': [data], 'layout' : go.Layout(xaxis=dict(range[min(X1),max(X1)]),
yaxis=dict(range=[min(Y1),max(Y1)]),
)
}
if _name_ == '_main_':
app.run_server(debug=True)
I expect, when select the value Alba from drop down and year 2015 to show me on table all the values related to this and to plot the CPT function of data.

Categories

Resources