Dash Plotly error : Stuck on Loading... page after server run - python

Could you please help me with this error.
The page stuck with loading.... message but never loads.
There's no error on server run.
This is my code:
import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import plotly.graph_objects as go
import numpy as np
df1 = pd.read_csv('lines.csv', encoding='latin-1', low_memory=False)
df1.rename(columns={"Order Type": "OrderType"}, inplace=True)
df1.loc[(df1.Processed != '?'), 'OrderTypeProcessed'] = df1['Qty']
df1.loc[(df1.Processed == '?'), 'OrderTypeProcessed'] = 0
df2 = df1.groupby('OrderType').sum()
df3 = df1.groupby(' Packout station Number').sum()
df4 = df1.groupby('Packout station Operator').sum()
df5 = df1.groupby('Product Category').sum()
df1.rename(columns={df1.columns[12]:'Received Time'}, inplace=True)
df6 = df1.groupby('Received Time').sum()
df7 = df1.groupby('Cut Off Time').sum()
df2.reset_index(inplace=True)
df3.reset_index(inplace=True)
df4.reset_index(inplace=True)
df5.reset_index(inplace=True)
df6.reset_index(inplace=True)
df7.reset_index(inplace=True)
df5['Product Category'] = df5['Product Category'].str.upper()
app = dash.Dash()
app.layout = html.Div([
html.H1(children = "Dashboard Para Gestão De Produção - Caio",
style = {'textAlign' : 'center',}),
html.Div(children = "_______________________________",
style = {'textAlign' : 'center',}),
dcc.Graph(
id = 'lines-chart',
figure = {
'data' : [
{'x': df2['OrderType'], 'y': df2['Qty'], 'type': 'bar', 'name': 'Dropado'},
{'x': df2['OrderType'], 'y': df2['OrderTypeProcessed'], 'type': 'bar', 'name': 'Realizado'}
],
'layout' : {
'title': 'Grafico'
}
}
)
])
if __name__ == '__main__':
app.run_server(port =4050)
Could you please take a look, I tried call assets in app, however it also didn't work.
Here is the page after server run.

Here is the image that not load in question.

Related

Use list as column input in dash datatable with dash version 2.4?

Is there a way to input a list into a newer dash version? I have seen some older examples online e.g. here that seem to be able to do it. If I just try to run the example- I keep on getting an Invalid error argument [...]- Expected one of type [string, number, boolean]. I am using the dash version 2.4.1
Using the example mentioned in the post above- I get the error
import dash
import dash_bootstrap_components as dbc
import pandas as pd
brand_name = ['merc', 'bmw']
driver = [['driver1', 'driver2'], ['driver3', 'driver14']]
df = pd.DataFrame({'brand_name': brand_name, 'driver': driver})
print(df)
df_dict = df.to_dict('records')
app = dash.Dash(__name__)
app.layout = dbc.Card(
dbc.CardBody(
[
dash.dash_table.DataTable(
id='homepage-table',
data=df_dict,
columns=[
{'name': 'brand_name', 'id': 'brand_name'},
{'name': 'driver', 'id': 'driver', 'presentation': 'markdown'}
],
)]))
if __name__ == '__main__':
app.run_server(debug=True, port=8080)

Dash Plotly callback inputs (Updates on Page Load)

I'm new to Dash and I'm trying to figure out how to set Callback inputs.
My Dash app has graphs that I want to dynamically update with new data on every page load (or refresh.)
I don't want to do it through user interaction such as dropdown, radio button...
To do so I have created hidden divs as callback inputs, but I'm not sure this is the proper way.
Is there any other approach that would be more suitable (or elegant) in this situation?
Please let me know if there’s something else in my code that needs to be changed.
This is my code:
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import pandas as pd
import plotly.graph_objs as go
import json
import plotly.express as px
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.config['suppress_callback_exceptions'] = True
data = [['Blue', 30], ['Red ', 20], ['Green', 60]]
df = pd.DataFrame(data, columns=['Color', 'Number'])
data1 = [['A', 10, 88], ['B ', 50, 45], ['C', 25, 120]]
df1 = pd.DataFrame(data1, columns=['Letter', 'Column1', 'Column2'])
def serve_layout():
slayout = html.Div(children=[
html.H1(children='Colors and Letters', style={'text-align': 'center'}),
html.Div([
html.Div(id='input-value', style={'display': 'none'}),
html.Div(id='intermediate-value', style={'display': 'none'}),
]),
html.Div([dcc.Graph(id='graph', style={'width': 1200,
"margin-left": "auto",
"margin-right": "auto",
}),
dcc.Graph(id='graph1', style={'width': 1200,
"margin-left": "auto",
"margin-right": "auto",
})]),
])
return slayout
#app.callback(Output('intermediate-value', 'children'),
[Input('input-value', 'value')])
def clean_data(value):
df_1 = df
df_2 = df1
datasets = {
'df_1': df_1.to_json(orient='split', date_format='iso'),
'df_2': df_2.to_json(orient='split', date_format='iso')
}
return json.dumps(datasets)
#app.callback(
Output('graph', 'figure'),
[Input('intermediate-value', 'children')])
def update_graph(cleaned_data):
datasets = json.loads(cleaned_data)
dff = pd.read_json(datasets['df_1'], orient='split')
fig = go.Figure(data=[go.Bar(x=dff['Color'], y=dff['Number'], text=dff['Number'], textposition='auto')],
layout=go.Layout())
return fig
#app.callback(
Output('graph1', 'figure'),
[Input('intermediate-value', 'children')])
def update_graph(cleaned_data):
datasets = json.loads(cleaned_data)
dff1 = pd.read_json(datasets['df_2'], orient='split')
fig1 = px.line(x=dff1['Letter'], y=dff1['Column1'], color=px.Constant('Column1'),
labels=dict(x='Letter', y='Column1', color='Letter'))
fig1.add_bar(x=dff1['Letter'], y=dff1['Column2'], name='Column2')
return fig1
app.layout = serve_layout
if __name__ == '__main__':
app.run_server(debug=True)
Thanks for any help on this matter.
If you only want to update the plots on page load / refresh, I would advise against any callbacks and instead directly load the figures.
This way, you can leave out all the hidden and intermediate values.
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import pandas as pd
import plotly.graph_objs as go
import json
import plotly.express as px
import numpy as np
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.config['suppress_callback_exceptions'] = True
def refresh_data():
data = [['Blue', 30], ['Red ', np.random.random(1)[0] * 10], ['Green', 60]]
df = pd.DataFrame(data, columns=['Color', 'Number'])
data1 = [['A', 10, 88], ['B ', 50, 45], ['C', 25, 120]]
df1 = pd.DataFrame(data1, columns=['Letter', 'Column1', 'Column2'])
return df, df1
def serve_layout():
plot_style = {'width': 1200,
"margin-left": "auto",
"margin-right": "auto",
}
slayout = html.Div(children=[
html.H1(children='Colors and Letters', style={'text-align': 'center'}),
html.Div(
[dcc.Graph(figure=get_graph(), id='graph', style=plot_style),
dcc.Graph(figure=get_graph1(), id='graph1', style=plot_style)]),
])
return slayout
def get_clean_data():
df_1, df_2 = refresh_data()
datasets = {
'df_1': df_1.to_json(orient='split', date_format='iso'),
'df_2': df_2.to_json(orient='split', date_format='iso')
}
return json.dumps(datasets)
def get_graph():
datasets = json.loads(get_clean_data())
dff = pd.read_json(datasets['df_1'], orient='split')
fig = go.Figure(data=[
go.Bar(x=dff['Color'], y=dff['Number'], text=dff['Number'],
textposition='auto')],
layout=go.Layout())
return fig
def get_graph1():
datasets = json.loads(get_clean_data())
dff1 = pd.read_json(datasets['df_2'], orient='split')
fig1 = px.line(x=dff1['Letter'], y=dff1['Column1'],
color=px.Constant('Column1'),
labels=dict(x='Letter', y='Column1', color='Letter'))
fig1.add_bar(x=dff1['Letter'], y=dff1['Column2'], name='Column2')
return fig1
app.layout = serve_layout
if __name__ == '__main__':
app.run_server(debug=True)

Dynamic update Dash Datatable from df

I'm creating an auto-update Dash datatable. The data is obtained from a SQL Server Query, passed to a Dataframe and displayed in the datatable:
import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
import dash_table
import pandas as pd
import numpy as np
import pyodbc
app = dash.Dash(__name__, external_stylesheets=[dbc.themes.MINTY, 'https://use.fontawesome.com/releases/v5.9.0/css/all.css'])
sql_query = ('''SELECT * FROM HOSVITAL.dbo.Censo_Diario
ORDER BY Dias_Estancia DESC''')
server = '#srv'
database = '#db'
username = '#usr'
password = '#pwd'
conn = pyodbc.connect('DRIVER={SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)
df = pd.read_sql(sql_query,conn)
df = df.apply(lambda x: x.str.strip()
if x.dtype == "object" else x) # Trim whitespaces
After that, i'm defining a function for connect to my DB and another function for get and clean the data and return it as a dict:
def connectSQLServer(conn):
connSQLServer = conn
return connSQLServer
def getData():
df2 = pd.DataFrame()
for idx in range(10):
data = pd.read_sql(sql_query,conn)
df2 = df.apply(lambda x: x.str.strip()
if x.dtype == "object" else x)
df2 = df2.append(data, ignore_index=True)
df2 = df2.drop_duplicates().sort_index()
return df2.to_dict('records')
I´m giving custom name to the df columns:
tblcols=[{'name': 'Pabellon', 'id': 'Pabellon'},
{'name': 'Cama', 'id': 'Cama'},
{'name': 'Cedula', 'id': 'Cedula'},
{'name': 'Tipo', 'id': 'Tipo'},
{'name': 'EPS', 'id': 'EPS'},
{'name': 'Nivel', 'id': 'Nivel'},
{'name': 'Ingreso', 'id': 'Ingreso'},
{'name': 'Nombre', 'id': 'Nombre'},
{'name': 'Edad', 'id': 'Edad'},
{'name': 'Cod', 'id': 'Cod'},
{'name': 'Diagnostico', 'id': 'Diagnostico'},
{'name': 'Fecha Ingreso', 'id': 'Fecha_Ingreso'},
{'name': 'Dias Estancia', 'id': 'Dias_Estancia'}
]
Create my layout adding a Dcc.interval for update the data every 5 seconds:
app.layout = html.Div([
html.H4('CN Dashboard'),
dcc.Interval('graph-update', interval = 5000, n_intervals = 0),
dbc.Container([
dash_table.DataTable(
sort_action='native',
id = 'table',
css=[{
'selector': '.dash-cell div.dash-cell-value',
'rule': 'display: inline; white-space: inherit; overflow: inherit; text-overflow: inherit;'
}],
data = getData(),
columns=tblcols,]
)
Finally, I create this callback for update the table:
#app.callback(
dash.dependencies.Output('table','data'),
[dash.dependencies.Input('graph-update', 'n_intervals')])
def updateTable(n):
return getData()
if __name__ == '__main__':
app.run_server(debug=False, host='0.0.0.0', port = 8070)
app.title = 'Tablero CN' # appears in browser title bar
So, this App is displaying the data and it´s updating as expected, but the problem is that all rows are being duplicated in the Output.
Any suggestions?
Thanks in advance.
Error(Invalid prop for this component) - basically it is stating that dash_bootstrap_components.Table does not support data argument where you are trying to push update using callback. dash table has this feature. seems you imported it in code but didn't use. As far as I know it can't be solved with dbc. you can use dash_table if you really want this callback.
Query Re-usability - if both queries are same why not define query as variable in top as you did with conn and pass it as argument.
example:
query = '''select * from table'''

Plotly/Dash -- range filter resets on hoverData

I am trying capture mouse hover events using Dash. I capture the position of the mouse using hoverData.
The problem appears when I filter the time series using the range selector or the range slider. The plot correctly reduces to the selected time, but when I hover it with the mouse it resets to the main view (whole main series).
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
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv")
app.layout = html.Div([
dcc.Graph(
id='stock-plot'
),
], className="container")
#app.callback(
Output('stock-plot', 'figure'),
[Input('stock-plot', 'hoverData')])
def drawStockPrice(hoverData):
traces = [go.Scatter(
x=df.Date,
y=df['AAPL.High'],
mode='lines',
opacity=0.7,
connectgaps=True),
]
return {'data': traces,
'layout': go.Layout(colorway=["#5E0DAC", '#FF4F00', '#375CB1', '#FF7400', '#FFF400', '#FF0056'],
height=600,
title=f"Closing prices",
xaxis={"title": "Date",
'rangeselector': {'buttons': list([{'count': 1, 'label': '1M',
'step': 'month',
'stepmode': 'backward'},
{'count': 6, 'label': '6M',
'step': 'month',
'stepmode': 'backward'},
{'step': 'all'}])},
'rangeslider': {'visible': True}, 'type': 'date'},
yaxis={"title": "Price (USD)"},
)}
if __name__ == '__main__':
app.run_server(debug=True)
I am sure there should be a better solution but this is what I got (Dash v1.6.0):
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, State
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv")
layout = go.Layout( colorway=["#5E0DAC", '#FF4F00', '#375CB1', '#FF7400', '#FFF400', '#FF0056'],
height=600,
title=f"Closing prices",
xaxis={"title": "Date",
'rangeselector': {'buttons': list([{'count': 1, 'label': '1M',
'step': 'month',
'stepmode': 'backward'},
{'count': 6, 'label': '6M',
'step': 'month',
'stepmode': 'backward'},
{'step': 'all'}]
),
},
'rangeslider': {'visible': True},
'type': 'date',
},
yaxis={"title": "Price (USD)"},
)
traces = [go.Scatter( x=df.Date,
y=df['AAPL.High'],
mode='lines',
opacity=0.7,
connectgaps=True
)]
app.layout = html.Div([
dcc.Graph(
id='stock-plot',
figure={
'data': traces,
'layout': layout
}
),
], className="container")
#app.callback(
Output('stock-plot', 'figure'),
[Input('stock-plot', 'hoverData'),
Input('stock-plot', 'relayoutData')],
[State('stock-plot', 'figure')]
)
def drawStockPrice(hoverData, selected, figure):
data = figure['data']
layout = figure['layout']
if selected is not None and 'xaxis.range' in selected:
layout['xaxis']['range'] = selected['xaxis.range']
return {'data': data,
'layout': layout
}
if __name__ == '__main__':
app.run_server(debug=True)

Plotly Dash Display Dynamic Number of Plots Based on SQL Query

I am trying to get the app to display multiple plots in grid format whenever a user changes the date input. This is what I have thus far. Although, when I run the app right now it only displays one, not ALL, of the graphs. I am not sure how to code this so that the number of graphs displayed is dynamic and that they take up just enough space on the screen of whoever is running the app.
import dash
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import pyodbc
from datetime import datetime as dt
app = dash.Dash()
app.layout = html.Div(children=[
html.Div(children='''
Enter Date:
'''),
dcc.DatePickerSingle(id='date_picker_single', date=dt(2017, 12, 18)),
html.Div(id='output-graphs'),
])
def connect_sql_server(driver, server, db):
conn_sql_server = pyodbc.connect(
r'DRIVER={' + driver + '};'
r'SERVER=' + server + ';'
r'DATABASE=' + db + ';'
r'Trusted_Connection=yes;',
autocommit=True
)
return conn_sql_server
#app.callback(
Output(component_id='output-graphs', component_property='children'),
[Input(component_id='date_picker_single', component_property='date')]
)
def update_graphs(input_date):
sql_conn = connect_sql_server('ODBC Driver 13 for SQL Server', 'Server', 'Database')
cursor = sql_conn.cursor()
cursor.execute(
"""
exec QCMonotonicityGraphs ?
""", [input_date])
rows = cursor.fetchall()
sql_data = []
for row in rows:
sql_data.append(list(row))
labels = ['strike', 'last', 'call_put', 'title']
df = pd.DataFrame.from_records(sql_data, columns=labels)
unique_titles = df.title.unique()
graphs = []
for unique_title in unique_titles:
title = unique_title
call_strike = []
call_last = []
for row in rows:
if row[2] == 'C' and row[3] == unique_title:
call_strike.append(row[0])
call_last.append(row[1])
put_strike = []
put_last = []
for row in rows:
if row[2] == 'P' and row[3] == unique_title:
put_strike.append(row[0])
put_last.append(row[1])
graphs.append(dcc.Graph(
id='example-graph',
figure={
'data': [
{
'x': call_strike,
'y': call_last,
'mode': 'lines+markers',
'name': 'call'
},
{
'x': put_strike,
'y': put_last,
'mode': 'lines+markers',
'name': 'put'
}
],
'layout': {
'title': title
}
}
))
return graphs
if __name__ == '__main__':
app.run_server(debug=True)
Example

Categories

Resources