How to make callback for DatePickerRange and Graph in Dash - python

I just started to use Plotly and Dash. I try to connect my interactive graph with calendar (DatePickerRange). Both off them display correctly, but not together. My figure doesn’t see the start and end dates.
My variable date is “session_date”. I don’t know how to use the start and end variable with session_date. The range from session_date.
I have started to put start_date and end_date to call-back, byt that didn't display correctly.
Could someone help me?
With regards
Dorota
# -----------------------------------
# Connect to database OR data source here
# -----------------------------------
...
# -----------------------------------
# Retrieve data from database
# -----------------------------------
curs = db.cursor()
testy = """SELECT o.ticker, o.issuer, o.session_date, o.open, o.close, o.min
FROM olhc AS o;"""
curs.execute(testy)
data = []
for x in curs:
data.append(x)
df = pd.DataFrame(data, columns=['ticker', 'issuer', 'session_date', 'open', 'close', 'min'])
# convert the 'Session_date' column to datetime format
df['session_date']= pd.to_datetime(df['session_date'])
# -----------------------------------
# Initialize the app
# -----------------------------------
# This application is using a custom
# CSS stylesheet to modify the default
# styles of the elements.
# -----------------------------------
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
colors = dict(background='#3333',
text='#21617A',
font='#21617A')
# -----------------------------------
# Define app layout
# -----------------------------------
app.layout = html.Div(children=[
html.H1(children='Close & Open prices for company',
style={'textAlign': 'center', 'color': colors['text']}
),
html.Div(children=[
html.Div(style={
'textAlign': 'center', 'color': colors['font']
},
children='''Financial Dashboard for FellowshipPL
'''),
dcc.DatePickerRange(
id='my-date-picker-range',
calendar_orientation='horizontal',
day_size=30,
first_day_of_week=1, # 0 Sunday
clearable=False,
with_portal=False, # True on the page
min_date_allowed=date(2010, 1, 1),
max_date_allowed=date(2021, 12, 31),
initial_visible_month=date(2020, 1, 1),
start_date=date(2020, 1, 1),
end_date=date(2021, 12, 31),
display_format='MMM Do, YYYY', # lots possibilities
updatemode='singledate'
),
html.Div(id='output-container-date-picker-range'),
# -----------------------------------
# Define Dropdown
# -----------------------------------
dcc.Dropdown(style={
'textAlign': 'left',
'color': colors['text']
},
id='issuer_selection',
options=[
{'label': i, 'value': i} for i in df.issuer.unique()
], multi=False,
placeholder='Filter by name of company ...'),
html.H3(id='text'),
dcc.Graph(id='indicators')])
])
# -----------------------------------
# Define first callback
# -----------------------------------
#app.callback(
Output('output-container-date-picker-range', 'children'),
[Input('my-date-picker-range', 'start_date'),
Input('my-date-picker-range', 'end_date')])
def update_output(start_date, end_date):
string_prefix = 'You have selected: '
if start_date is not None:
start_date_object = date.fromisoformat(start_date)
start_date_string = start_date_object.strftime('%B %d, %Y')
string_prefix = string_prefix + 'Start Date: ' + start_date_string + ' | '
if end_date is not None:
end_date_object = date.fromisoformat(end_date)
end_date_string = end_date_object.strftime('%B %d, %Y')
string_prefix = string_prefix + 'End Date: ' + end_date_string
if len(string_prefix) == len('You have selected: '):
return 'Select a date to see it displayed here'
else:
return string_prefix
# #app.callback(
# Output('indicators', 'figure'),
# [Input('issuer_selection', 'value'),
# Input('my-date-picker-range', 'start_date'),
# Input('my-date-picker-range', 'end_date')])
#app.callback(
Output('indicators', 'figure'),
[Input('issuer_selection', 'value')])
def retrieve_plots(issuer):
filtered_df = df[df['issuer'] == issuer]
# dff = df.loc[start_date:end_date]
# Creating trace1
trace1 = go.Scatter(x=(filtered_df['session_date']),
y=filtered_df['close'],
mode="markers",
name="Close price",
marker=dict(color='#21617A', size=4),
text=filtered_df['session_date'])
# Creating trace2
trace2 = go.Scatter(x=(filtered_df['session_date']),
y=filtered_df['open'],
mode="markers",
name="Open price",
marker=dict(color='#C22E4C', size=3),
text=filtered_df.session_date)
# Creating trace3
trace3 = go.Scatter(x=(filtered_df['session_date']),
y=filtered_df['min'],
mode="markers",
name="Min price",
marker=dict(color='#7FD13A', size=2),
text=filtered_df.session_date)
data = [trace1, trace2, trace3]
layout = dict(yaxis=dict(title='Prices', ticklen=5, zeroline=False),
xaxis=dict(title='Date', ticklen=5, zeroline=False),
hovermode="x unified",
style={'textAlign': 'center',
'color': colors['text']
},
)
datapoints = {'data': data, 'layout': layout}
return datapoints
# -----------------------------------
# Run the app
# -----------------------------------
if __name__ == '__main__':
app.run_server(debug=True)

Related

Trying to get a value from a df to use as a value for axis range in an indicator axis

I have been trying to put together a Plotly Dash app that will pull up our clients current hours and historical hours with the current hours being represented as a gauge of how many have been used versus how many are allowed, which varies from client to client so there is no set value I can input as an overall value. So, value = hours spent and range is [0, hours allowed]
I have tried using .iloc, and .values but neither have worked to single out the integer as an independent variable to be used. However, I also have a feeling that I am screwing something up in general with the dash, so if anyone can help me unscrew this so I can get it presented by Friday would be lovely.
Edit
#mozway, sorry about that (also, apparently enter sends). The csv looks like this:
Client | Hours Spent | Hours Allowed | Last Updated
XXXX | 30.81 | 60 | 2021-09-07
And so on. As for pinpoint, it gives me a error at the Indicator figure
elif client != "All":
dff = dfhours.query('Client == "{}"'.format(client))
ha = dff.values[0][5]
fig = go.Figure(go.Indicator(
domain = {'x': [0, 1], 'y': [0, 1]},
value = dff['Hours Spent'],
mode = "gauge+number",
gauge = {'axis': {'range':[None, ha]}}))
ValueError:
Invalid value of type 'pandas.core.series.Series' received
for the 'value' property of indicator
Received value: 0 30.81
Name: Hours Spent, dtype: float64
The 'value' property is a number and may be specified as:
- An int or float
It is supposed to use the values from Hours Spent as the Value for the gauge, and the Hours Allowed as the end of the gauge.
End Edit
app = dash.Dash(__name__)
dfhours = pd.read_csv("hothours9-7.csv")
dfhours['Last Updated'] = pd.to_datetime(dfhours['Last Updated'])
dfclients = pd.read_csv("hotclients9-7.csv")
clients = clientlist['Client'].unique()
app.layout = html.Div(children=[
html.H1(
children='Hello!',
style={
'textAlign': 'center'
}
),
html.Br(),
html.Div([
html.Label('Clients'),
dcc.Dropdown(
id='clients-list',
options=[{'label': i, 'value': i} for i in clients],
value='All',
style = {'width': "80%"}
),
dcc.Dropdown(
id='info-drop',
options = [{'label': i, 'value': i} for i in ['Historical Hours', 'Current Hours']],
value = 'Current Hours',
)
]),
html.Br(),
dcc.Graph(id='info-graph')
])
#-------------------------------------------
#app.callback(
Output('info-graph','figure'),
[Input('clients-list','value'),
Input('info-drop','value')])
def update_graph(client,info):
if info == "Current Hours":
if client == "All":
fig = px.bar(dfhours, x="Client", y="Hours Spent")
elif client != "All":
dff = dfhours.query('Client == "{}"'.format(client))
ha = dff.values[0][5]
fig = go.Figure(go.Indicator(
domain = {'x': [0, 1], 'y': [0, 1]},
value = dff['Hours Spent'],
mode = "gauge+number",
gauge = {'axis': {'range':[None, ha]}}))
elif info == 'Historical Hours':
if client == "All":
dcc.Checklist(
options = [{"label": x, "value": x} for x in dfclients['Client']]),
fig = px.line(dfclients,x="Last Updated",y="Hours Spent",color="Client")
elif client != "All":
dff = dfclients.query('Client == "{}"'.format(client)),
fig = px.line(dff, x="Last Updated",y="Hours Spent")
return fig
if __name__=='__main__':
app.run_server(debug=False)
have simulated your data...
simple case of reset_index() after filtering dataframe then allows you to always access row as index 0 (assumes one row per client)
have used dash 1.0.0 hence html and dcc packages are not imported but referenced
you construct checklist in callback that is not used anywhere...
from jupyter_dash import JupyterDash
import dash
from dash.dependencies import Input, Output, State
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
# app = dash.Dash(__name__)
app = JupyterDash(__name__)
# dfhours = pd.read_csv("hothours9-7.csv")
# dfhours['Last Updated'] = pd.to_datetime(dfhours['Last Updated'])
# dfclients = pd.read_csv("hotclients9-7.csv")
# simulate data...
h = np.random.uniform(10, 40, 4)
dfhours = pd.DataFrame(
{
"Client": list("ABCD"),
"Hours Spent": h,
"Hours Allowed": h * np.random.uniform(1.5, 2, 4),
}
)
clientlist = pd.DataFrame({"Client": list("ABCD")})
clients = clientlist["Client"].unique()
dfclients = pd.DataFrame(
{
"Last Updated": pd.date_range("1-May-2021", periods=60),
"Client": np.random.choice(list("ABCD"), 60),
"Hours Spent": np.random.uniform(10, 40, 60),
}
)
app.layout = dash.html.Div(
children=[
dash.html.H1(children="Hello!", style={"textAlign": "center"}),
dash.html.Br(),
dash.html.Div(
[
dash.html.Label("Clients"),
dash.dcc.Dropdown(
id="clients-list",
options=[{"label": i, "value": i} for i in clients],
value="All",
style={"width": "80%"},
),
dash.dcc.Dropdown(
id="info-drop",
options=[
{"label": i, "value": i}
for i in ["Historical Hours", "Current Hours"]
],
value="Current Hours",
),
]
),
dash.html.Br(),
dash.dcc.Graph(id="info-graph"),
]
)
# -------------------------------------------
#app.callback(
Output("info-graph", "figure"),
[Input("clients-list", "value"), Input("info-drop", "value")],
)
def update_graph(client, info):
if info == "Current Hours":
if client == "All":
fig = px.bar(dfhours, x="Client", y="Hours Spent")
elif client != "All":
dff = dfhours.loc[dfhours["Client"].eq(client)].reset_index(drop=True)
fig = go.Figure(
go.Indicator(
domain={"x": [0, 1], "y": [0, 1]},
value=dff.loc[0, "Hours Spent"],
mode="gauge+number",
gauge={"axis": {"range": [0, dff.loc[0, "Hours Allowed"]]}},
)
)
elif info == "Historical Hours":
if client == "All":
# this is spurious !!!
dash.dcc.Checklist(
options=[{"label": x, "value": x} for x in dfclients["Client"]]
),
fig = px.line(dfclients, x="Last Updated", y="Hours Spent", color="Client")
elif client != "All":
dff = dfclients.query('Client == "{}"'.format(client))
fig = px.line(dff, x="Last Updated", y="Hours Spent")
return fig
if __name__ == "__main__":
# app.run_server(debug=False)
app.run_server(mode="inline")

Why is my graph not changing when I select it in dropdown?

Why my graph is not changing when I select it in dropdown?
Here is my code:
# Step 1. Launch the application
app = dash.Dash()
# Step 2. Import the dataset
df = pd.read_excel("./billingdata.xlsx")
# Step 3. Create a plotly figure
trace_1 = px.Scatter(
x=df.OVERAGE_ACCOUNTS_PER_CYCLE,
y=df.CORP_ID,
name="BILLING_CYCLE_START_DATE", # marker=dict(color='#ffcdd2'))
line=dict(width=1, color="rgb(229, 151, 50)"),
)
layout = px.Layout(title="Billing cycle", hovermode="closest")
fig = px.Figure(data=[trace_1], layout=layout)
# Step 4. Create a Dash layout
features = df.columns[1]
opts = [{"label": i, "value": i} for i in sorted(df.BILLING_CYCLE_START_DATE)]
app.layout = html.Div(
[
# adding a plot
dcc.Graph(id="plot", figure=fig),
# dropdown
html.P(
[
html.Label("BILLING_CYCLE_START_DATE"),
dcc.Dropdown(id="opt", options=opts, value=opts[0]["value"]),
],
style={
"width": "400px",
"fontSize": "20px",
"padding-left": "100px",
"display": "inline-block",
},
),
]
)
# Step 5. Add callback functions
#app.callback(
dash.dependencies.Output("plot", "figure"),
[dash.dependencies.Input("opt", "value")],
)
def update_figure(X):
dff = df[df.BILLING_CYCLE_START_DATE == X]
trace_2 = px.Scatter(
x=dff.OVERAGE_ACCOUNTS_PER_CYCLE,
y=dff.CORP_ID,
name=X,
line=dict(width=2, color="rgb(106, 181, 135)"),
)
fig = px.Figure(data=[trace_1, trace_2], layout=layout)
return fig.update_traces(mode="markers+lines")
# Step 6. Add the server clause
if __name__ == "__main__":
app.run_server(debug=True)

Create a Chart in dash-plot based on dropdown and date picker for a certain unique value

I have a simple database as in the below picture:
and the query looks like:
SELECT
[Date]
,[eNodeBName]
,[Downlinkbandwidth]
,[DownlinkEARFCN]
,[CellName]
,[LocalCellId]
,[PhysicalcellID]
,[LRRCConnReqAtt]
,[RRCSetupSuccessRate]
,[InterFreqSuccessRate4G]
,[IntraRATHOSucccessRate]
,[IntraFreqSuccessRate4G]
,[CellDLMaxThroughputMbps]
,[CellDownlinkAverageThroughputMbps]
FROM [myDB].[dbo].[input]
Now I need to create an interactive chart which depends on inputs like a date picker and drop down list.
As this is the sample GUI I created to figure chart throw this inputs as shown in the below picture:
Now I am creating chart based on the below columns name as in the below picture:
as this is the related query as the below:
SELECT
[Date]
,[CellName]
,[LRRCConnReqAtt]
,[RRCSetupSuccessRate]
,[InterFreqSuccessRate4G]
,[IntraRATHOSucccessRate]
,[IntraFreqSuccessRate4G]
,[CellDLMaxThroughputMbps]
,[CellDownlinkAverageThroughputMbps]
FROM [myDB].[dbo].[input]
So now the X-axis should be the Date column and the y-axis related to those below columns is the KPI columns:
SELECT
[LRRCConnReqAtt]
,[RRCSetupSuccessRate]
,[InterFreqSuccessRate4G]
,[IntraRATHOSucccessRate]
,[IntraFreqSuccessRate4G]
,[CellDLMaxThroughputMbps]
,[CellDownlinkAverageThroughputMbps]
FROM [myDB].[dbo].[input]
So now we have a unique column contains unique values is called CellName, this cell name I want create a simple chart for this unique value based on date columnn and KPI column.
So for example I want to show a line chart for a certain CellName = 2002334 for KPI LRRCConnReqAtt based on data from 27 of December to 9 of January. So I need a chart as the below picture and this is an example chart created in Excel.
and this is my code:
import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
from sqlalchemy import create_engine
import datetime
from datetime import datetime as dt
from dash.dependencies import Input, Output
# connect db
engine = create_engine('mssql+pyodbc://xxxxxx\SMxxxxxARTRNO_EXPRESS/myDB?driver=SQL+Server+Native+Client+11.0')
cursor = engine.raw_connection().cursor()
start = datetime.datetime(2019, 12, 2)
end = datetime.datetime(2019, 12, 15)
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
lte_kpis = pd.read_sql('SELECT * FROM [myDB].[dbo].[input]',
engine)
lte_kpis_raw = pd.read_sql('SELECT LRRCConnReqAtt, RRCSetupSuccessRate, InterFreqSuccessRate4G, IntraRATHOSucccessRate, IntraFreqSuccessRate4G,CellDLMaxThroughputMbps, CellDownlinkAverageThroughputMbps FROM [myDB].[dbo].[input]',
engine)
scale_1 = ['LRRCConnReqAtt']
scale_2 = ['RRCSetupSuccessRate', 'InterFreqSuccessRate4G', 'IntraRATHOSucccessRate', 'IntraFreqSuccessRate4G']
scale_3 = ['CellDLMaxThroughputMbps', 'CellDownlinkAverageThroughputMbps']
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 1000)
availble_cell = lte_kpis['CellName'].unique()
# availble_cell = lte_kpis.unique(lte_kpis[['Date', 'Site Name', 'Cell CI', 'Cell LAC']].values.ravel('K'))
app.layout = html.Div([
dcc.Dropdown(
id='cell-name-xaxis-column',
options=[{'label': i, 'value': i} for i in availble_cell],
value='2205516'
),
dcc.Dropdown(
id='myColumns',
options=[{'label': col, 'value': col} for col in lte_kpis_raw.columns],
multi=True,
value='LRRCConnReqAtt'
),
dcc.DatePickerRange(
id='my-date-picker-range',
min_date_allowed=dt(1995, 8, 5),
max_date_allowed=dt(2030, 9, 19),
initial_visible_month=dt(2019, 10, 5),
start_date=dt(2019, 10, 1),
end_date=dt(2020, 1, 1)
),
html.Div(id='output-container-date-picker-range'),
dcc.Graph(
style={'height': 300},
id='my-graph'
)
])
#app.callback(
Output('my-graph', 'figure'),
[Input('cell-name-xaxis-column', 'value'),
Input('myColumns', 'value')])
def update_graph(xaxis_column_name, yaxis_column_name, date_value):
dff = lte_kpis[lte_kpis['Date'] == date_value]
return {
'data': [dict(
x=dff[dff['Date'] == xaxis_column_name]['Value'],
y=dff[dff['Date'] == yaxis_column_name]['Value'],
text=dff[dff['Date'] == yaxis_column_name]['CellName'],
mode='line',
line={
'size': 15,
'opacity': 0.5
}
)],
}
if __name__ == '__main__':
app.run_server(debug=True)
Note that I want to put more than one KPI in one chart with different plots....
As the scale values in those KPI are little bit different so I tried to create a three types of objects with columns name scale values as the below code
scale_1 = ['LRRCConnReqAtt']
scale_2 = ['RRCSetupSuccessRate', 'InterFreqSuccessRate4G', 'IntraRATHOSucccessRate', 'IntraFreqSuccessRate4G']
scale_3 = ['CellDLMaxThroughputMbps', 'CellDownlinkAverageThroughputMbps']
and this is the error I found:
TypeError: update_graph() missing 1 required positional argument: 'date_value'
Traceback (most recent call last)
File "C:\Users\mwx825326\PycharmProjects\MyReference\venv\Lib\site-packages\dash\dash.py", line 1337, in add_context
output_value = func(*args, **kwargs) # %% callback invoked %%
TypeError: update_graph() missing 1 required positional argument: 'date_value'
Traceback (most recent call last):
File "C:\Users\mwx825326\PycharmProjects\MyReference\venv\Lib\site-packages\dash\dash.py", line 1337, in add_context
output_value = func(*args, **kwargs) # %% callback invoked %%
TypeError: update_graph() missing 1 required positional argument: 'date_value'
Any assistance appreciated.!!!!
Now this question is solved..
But I need it in more static way ,and the way I have to remove one Drop-down and create a chart based on one Drop-down and Date-Picker instead of 2 Drop-down as the removable drop down is based on Columns in DB in y-axis...
First I created Arrays for every Column should be the y-axis column, as I want to make it static charts for every multi or single Column in one Chart based on another Column or multiple Columns value in database....
as the below code:
SHOW_COLUMNS1 = [
'lrrc_re_est_succ',
'cell_dl_max_throughput'
]
SHOW_COLUMNS2 = [
'interfreq_success_rate_4g',
'intrarat_ho_success_rate'
]
SHOW_COLUMNS3 = [
'rcc_setup_success_rate',
'interfreq_success_rate_4g'
]
SHOW_COLUMNS4 = [
'cell_downlink_average_throughput'
]
after that the connection to the Date-Base
# connect db
engine = create_engine('mssql+pyodbc://xxxxxx\zzzzzz/myDB?driver=SQL+Server+Native+Client+11.0')
cursor = engine.raw_connection().cursor()
lte_kpis = pd.read_sql('SELECT * FROM [myDB].[dbo].[lte_details]', engine)
after that I created a GUI for the interactive Charts and pandas read as the below code:
lte_kpis = pd.read_sql('SELECT * FROM [myDB].[dbo].[lte_details]', engine)
pd.set_option('display.max_columns', 10000)
print(lte_kpis)
lte_kpis.set_index('date', inplace=True)
availble_cell = lte_kpis['cell_name'].unique()
plots = []
app.layout = html.Div([
html.H5(
'Huawei KPI Dashbord'),
html.Label('Choose the "Cell-Name"'),
dcc.Dropdown(
id='cell-name-xaxis-column',
options=[{'label': i, 'value': i} for i in availble_cell],
value= availble_cell[0]
),
html.Label('Choose Date Destination'),
dcc.DatePickerRange(
id='date-picker-range',
min_date_allowed=dt(1995, 8, 5),
max_date_allowed=dt(2030, 9, 19),
initial_visible_month=dt(2019, 10, 5),
start_date=dt(2019, 10, 1),
end_date=dt(2020, 1, 1)
),
html.Div(id='output-container-date-picker-range-%s'),
dcc.Dropdown(
id='yaxis-columns',
options=[{'label': col, 'value': col} for col in SHOW_COLUMNS1],
multi=True,
disabled=True,
value=[SHOW_COLUMNS1[0], SHOW_COLUMNS1[1]]
),
dcc.Graph(
style={'height': 300},
id='my-graph'
),
dcc.Dropdown(
id='yaxis-columns2',
options=[{'label': col, 'value': col} for col in SHOW_COLUMNS2],
multi=True,
disabled=True,
value=[SHOW_COLUMNS2[0], SHOW_COLUMNS2[1]]
),
dcc.Graph(
style={'height': 300},
id='my-graph2'
),
dcc.Dropdown(
id='yaxis-columns3',
options=[{'label': col, 'value': col} for col in SHOW_COLUMNS3],
multi=True,
disabled=True,
value=[SHOW_COLUMNS3[0], SHOW_COLUMNS3[1]]
),
dcc.Graph(
style={'height': 300},
id='my-graph3'
),
dcc.Dropdown(
id='yaxis-columns4',
options=[{'label': col, 'value': col} for col in SHOW_COLUMNS4],
multi=True,
disabled=True,
value=[SHOW_COLUMNS4[0]]
),
dcc.Graph(
style={'height': 300},
id='my-graph4'
),
])
and this is Call-back
#app.callback(
Output(component_id='my-graph2', component_property='figure'),
[Input(component_id='cell-name-xaxis-column', component_property='value'),
Input(component_id='yaxis-columns2', component_property='value'),
Input(component_id='date-picker-range', component_property='start_date'),
Input(component_id='date-picker-range', component_property='end_date')])
def update_graph(cell_name, yaxis_cols, start_date, end_date):
if not isinstance(yaxis_cols, list):
yaxis_cols = [yaxis_cols]
print(yaxis_cols)
print((start_date, end_date))
sql_statement = "SELECT date, %s, %s FROM [myDB].[dbo].[lte_details] WHERE ([cell_name]='%s' AND [date]>='%s' AND [date]<='%s')" \
% (SHOW_COLUMNS2[0], SHOW_COLUMNS2[1], cell_name, start_date, end_date)
df = pd.read_sql(sql_statement, engine)
scatters = []
for col in yaxis_cols:
if col == 'lrrc_conn_req_att':
scatters.append(go.Bar(
x=df['date'],
y=df[col],
mode='lines',
name=col
))
else:
scatters.append(go.Scatter(
x=df['date'],
y=df[col],
name=col
))
figure = {
'data': scatters,
}
return figure
Note that as the previous error is related to the missing of data type in data base when importing the excel file to the data base related to the below Code:
col_dict = {
'date': 'Date',
'enodeb_name': 'eNodeB Name',
'downlink_bandwidth': 'Downlink bandwidth',
...........................
}
LTE_DETAILS_TABLE = 'lte_details'
cols = list(col_dict.keys())
# connect db
engine = create_engine('mssql+pyodbc://xxxxx\xxxxxx/myDB?driver=SQL+Server+Native+Client+11.0')
connection = engine.connect()
meta = MetaData()
ltedetails = Table(
LTE_DETAILS_TABLE, meta,
Column('id', Integer, primary_key=True),
Column(cols[0], Date),
Column(cols[1], String),
Column(cols[2], String),
.................................
)
if engine.dialect.has_table(engine, LTE_DETAILS_TABLE):
ltedetails.drop(engine)
meta.create_all(engine)
lte_df = pd.read_excel(os.path.join(os.path.dirname(__file__), 'input.xlsx'), sheet_name='LTE Details', dtype={
col_dict[cols[0]]: str,
col_dict[cols[1]]: str,
col_dict[cols[2]]: str,
.....................................
})
lte_df['Date'] = pd.to_datetime(lte_df['Date'], errors='coerce')
query = db.insert(ltedetails)
values_list = []
row_count = 1
for i in lte_df.index:
row = lte_df.loc[i]
record = {'id': row_count}
for col in col_dict.keys():
if col == cols[3] or col == cols[4] or col == cols[5] or col == cols[6] or col == cols[7] or col == cols[8]:
record[col] = int(row[col_dict[col]])
elif col == cols[9] or col == cols[10] or col == cols[11] or col == cols[12] or col == cols[13] or col == cols[14]:
record[col] = float(row[col_dict[col]])
else:
record[col] = row[col_dict[col]]
values_list.append(record)
row_count += 1
ResultProxy = engine.execute(query, values_list)
connection.close()
engine.dispose()
So I stuck now the I want to remove the Dropp-down with id ``which called id='yaxis-columns', ...
So If there's any comment about how to improve this code performance and Complete to solve my issue..
I am glad for that.

How to handle a callback in Dash Plot for Graph based on Specific Inputs from User in Dash Plot

I am trying to handle a callback by return a simple Graph based on Drop-Down and Date-Picker Inputs after Click Submit Button....
So to explain in deep,
Example:
As for the below Image, let's imagine that this is the final result I need to be looks like:
So Here's a simple of Data-base looks like I use as the Below Image:
Ok Lets Explain In-Deep:
Now I need to Out-Put a Simple Graph That's Shows a simple line with the values based on the below Input:
1st Drop-Down contains the CellName values like in the Database
2nd Drop-Down Contains the list of specific Column Names I want to out-put in the Graph.
3rd Date-Picker Contains all the dates which was in the Date Column in the previous DB Picture.
Finally I want Click this button to Generate the Graph.
So Here's My Code as the below:
import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
from sqlalchemy import create_engine
import datetime
from datetime import datetime as dt
from dash.dependencies import Input, Output
# connect db
engine = create_engine('mssql+pyodbc://WWX542337CDCD\SMARTRNO_EXPRESS/myDB?driver=SQL+Server+Native+Client+11.0')
cursor = engine.raw_connection().cursor()
start = datetime.datetime(2019, 12, 2)
end = datetime.datetime(2019, 12, 15)
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
gsm_kpis = pd.read_sql('SELECT * FROM [myDB].[dbo].[mnm_rotterdam_5_daily_details-20191216081027]',
engine)
gsm_kpis_raw = pd.read_sql('SELECT Voice_SetupFailRate_2G, '
'Voice_DropRate_2G, Packet_SetupFailRate_2G, '
'OutgHandover_SuccesRate_2G, Voice_ErlHr_2G, Packet_DLMBytes_2G, Packet_ULMBytes_2G, '
'Availability_2G FROM [myDB].[dbo].[mnm_rotterdam_5_daily_details-20191216081027]',
engine)
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 1000)
availble_cell = gsm_kpis['CellName'].unique()
app.layout = html.Div([
dcc.Dropdown(
id='cell-name-xaxis-column',
options=[{'label': i, 'value': i} for i in availble_cell],
value='11063'
),
dcc.Dropdown(
id='myColumns',
options=[{'label': col, 'value': col} for col in gsm_kpis_raw.columns],
value='Voice_SetupFailRate_2G'
),
dcc.DatePickerRange(
id='my-date-picker-range',
min_date_allowed=dt(1995, 8, 5),
max_date_allowed=dt(2030, 9, 19),
initial_visible_month=dt(2019, 10, 5),
start_date=dt(2019, 10, 1),
end_date=dt(2020, 1, 1)
),
html.Div(id='output-container-date-picker-range'),
html.Button('Submit', id='button'),
dcc.Graph(
style={'height': 300},
id='my-graph'
)
])
#app.callback(
Output('my-graph', 'figure'),
[Input('cell-name-xaxis-column', 'value'),
Input('myColumns', 'value')])
def update_graph(xaxis_column_name, yaxis_column_name, date_value):
dff = gsm_kpis[gsm_kpis['Date'] == date_value]
return {
'data': [dict(
x = dff[dff['Date'] == xaxis_column_name]['Value'],
y = dff[dff['Date'] == yaxis_column_name]['Value'],
text = dff[dff['Date'] == yaxis_column_name]['Cell Name'],
mode = 'line',
line = {
'size': 15,
'opacity': 0.5
}
)],
}
if __name__ == '__main__':
app.run_server(debug=True)
and this is the Error I find:
TypeError: update_graph() missing 1 required positional argument: 'date_value'
I think there's a problem with handeling the Call-Back function...
Anyone Could help me how Can I handle this?
I hope everything will be clear...
Note: not Important to use the Submit button
In this part:
#app.callback(
Output('my-graph', 'figure'),
[Input('cell-name-xaxis-column', 'value'),
Input('myColumns', 'value')])
def update_graph(xaxis_column_name, yaxis_column_name, date_value):
You have not made an Input for date_value, but as your date selection control is a range picker, you'll need to supply a start and end Input, as follows:
#app.callback(
Output('my-graph', 'figure'),
[Input('cell-name-xaxis-column', 'value'),
Input('myColumns', 'value'),
Input('my-date-picker-range', 'start_date'),
Input('my-date-picker-range', 'end_date')])
def update_graph(xaxis_column_name, yaxis_column_name, start_date, end_date):
And change your update_graph code as appropriate.

How to remove the drop down list and make it static instead, using dash plot

I have just create a simple Dashboard for a simple database in SQL based on two drop down list and a date picker.
So this related chart the x-axis based on the date and that was constant, and the y-axis based on DropDownlist value, So this was not constant as-well, as the chart based also on another drop-down with another columns value as this is a unique value I want to plot a graph on it....
Now I need to change a bit of sequence in this code as I want to show the graph based on the Date-time-picker and the unique value only and remove the other drop-down list
So this is my full code
import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
from sqlalchemy import create_engine
import datetime
from datetime import datetime as dt
from dash.dependencies import Input, Output
import plotly.graph_objs as go
import plotly.express as px
import hypothesis
import pytest
# 'LRRCConnReqAtt',
SHOW_COLUMNS1 = [
'lrrc_re_est_succ',
'cell_dl_max_throughput'
]
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
# connect db
engine = create_engine('mssql+pyodbc://xxxx\xxxx/myDB?driver=SQL+Server+Native+Client+11.0')
cursor = engine.raw_connection().cursor()
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
lte_kpis = pd.read_sql('SELECT * FROM [myDB].[dbo].[lte_details]', engine)
pd.set_option('display.max_columns', 10000)
print(lte_kpis)
lte_kpis.set_index('date', inplace=True)
availble_cell = lte_kpis['cell_name'].unique()
app.layout = html.Div([
html.H5(
'Dashbord'),
html.Label('Choose the "Cell-Name"'),
dcc.Dropdown(
id='cell-name-xaxis-column',
options=[{'label': i, 'value': i} for i in availble_cell],
value=availble_cell[0]
),
html.Label('Choose Date Destination'),
dcc.DatePickerRange(
id='date-picker-range',
min_date_allowed=dt(1995, 8, 5),
max_date_allowed=dt(2030, 9, 19),
initial_visible_month=dt(2019, 10, 5),
start_date=dt(2019, 10, 1),
end_date=dt(2020, 1, 1)
),
html.Div(id='output-container-date-picker-range-%s'),
dcc.Dropdown(
id='yaxis-columns',
options=[{'label': col, 'value': col} for col in SHOW_COLUMNS1],
multi=True,
disabled=True,
value=[SHOW_COLUMNS1[0], SHOW_COLUMNS1[1]]
),
dcc.Graph(
style={'height': 300},
id='my-graph'
),
])
#app.callback(
Output(component_id='my-graph', component_property='figure'),
[Input(component_id='cell-name-xaxis-column', component_property='value'),
Input(component_id='yaxis-columns', component_property='value'),
Input(component_id='date-picker-range', component_property='start_date'),
Input(component_id='date-picker-range', component_property='end_date')])
def update_graph(cell_name, yaxis_cols, start_date, end_date):
if not isinstance(yaxis_cols, list):
yaxis_cols = [yaxis_cols]
print(yaxis_cols)
print((start_date, end_date))
sql_statement = "SELECT date, %s, %s FROM [myDB].[dbo].[lte_details] WHERE ([cell_name]='%s' AND [date]>='%s' AND [date]<='%s')" \
% (SHOW_COLUMNS1[0], SHOW_COLUMNS1[1], cell_name, start_date, end_date)
df = pd.read_sql(sql_statement, engine)
scatters = []
for col in yaxis_cols:
if col == 'lrrc_conn_req_att':
scatters.append(go.Bar(
x=df['date'],
y=df[col],
mode='lines',
name=col
))
else:
scatters.append(go.Scatter(
x=df['date'],
y=df[col],
name=col
))
figure = {
'data': scatters,
}
So now I want to remove the below core-component
dcc.Dropdown(
id='yaxis-columns',
options=[{'label': col, 'value': col} for col in SHOW_COLUMNS1],
multi=True,
disabled=True,
value=[SHOW_COLUMNS1[0], SHOW_COLUMNS1[1]]
),
and make the graph static on those values only related to SQL query
SHOW_COLUMNS1 = [
'lrrc_re_est_succ',
'cell_dl_max_throughput'
]
Or I want to hide it I just do not use and show this radio button....
I tried to change it but find some error
this is the GUI looks Like
I want to be like this as the below figure
as this is the SQL Query Should be
sql_statement = "SELECT date, lrrc_re_est_succ, cell_dl_max_throughput FROM [myDB].[dbo].[lte_details] WHERE ([cell_name]='%s' AND [date]>='%s' AND [date]<='%s')" \
% (cell_name, start_date, end_date)
As you said, you need to remove the code that creates the component with id yaxis-columns.
Exclude this component's value from the inputs and internals of your callback function. I believe this will work:
#app.callback(
Output(component_id='my-graph', component_property='figure'),
[Input(component_id='cell-name-xaxis-column', component_property='value'),
Input(component_id='date-picker-range', component_property='start_date'),
Input(component_id='date-picker-range', component_property='end_date')])
def update_graph(cell_name, start_date, end_date):
sql_statement = "SELECT date, lrrc_re_est_succ, cell_dl_max_throughput FROM [myDB].[dbo].[lte_details] WHERE ([cell_name]='%s' AND [date]>='%s' AND [date]<='%s')" \
% (cell_name, start_date, end_date)
df = pd.read_sql(sql_statement, engine)
scatters = []
for item in ['lrrc_re_est_succ', 'cell_dl_max_throughput']:
scatters.append(go.Bar(
x=df['date'],
y=df[item],
mode='lines',
name=item
))
figure = {'data': scatters}
return figure

Categories