I just started learning dash plotly. There are no problems with building a drawing. I think this is a great library for data visualization. But I ran into the fact that the data in the chart is not updated. My data is in the database and is being recorded all the time. I am using pandas for rendering.
Here is my code:
import sqlite3
import pandas as pd
from datetime import datetime
import pytz
import numpy as np
import dash
import dash_core_components as dcc
import dash_html_components as html
timezone = pytz.timezone("Etc/UTC")
utc_from = datetime(2021, 3, 23, tzinfo=timezone)
#Создает новый файл , если он есть то просто подключается
base = sqlite3.connect('base_eurousd.db')
cur = base.cursor()
read_db = cur.execute('SELECT * FROM data_eurusd').fetchall()
df = pd.DataFrame(read_db)
#d = pd.read_sql("select * from data", db_conn)
print(df)
df[0] = pd.to_datetime(df[0], unit='ms')
df[3] = np.where(df[1].diff().lt(0)|df[2].diff().lt(0), df[3]*-1, df[3])
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.layout = html.Div(children=[
html.H1(children='HELLO DASH'),
html.H2(children='My first dash'),
html.Div(children='''Dash : A web application framework for Python'''),
dcc.Graph(
id='example-graph',
figure={
'data': [
{'x':df[0], 'y':df[1], 'name': 'BID', 'marker': {'color': 'red'}},
{'x':df[0], 'y':df[2], 'name': 'ASK', 'marker': {'color': 'blue'}},
],
'layout' : {
'title': 'TEST'
}
}
)
])
if __name__ == '__main__' :
app.run_server(debug=True)
df output:
0 1 2 3
0 1623066946305 1.21623 1.21625 2
1 1623066946432 1.21622 1.21625 2
2 1623066947746 1.21621 1.21624 6
3 1623066949244 1.21621 1.21623 4
4 1623066949587 1.21621 1.21624 4
... ... ... ... ..
85715 1623171716674 1.21840 1.21842 2
85716 1623171716808 1.21841 1.21843 6
85717 1623171717070 1.21841 1.21842 4
85718 1623171717419 1.21839 1.21841 6
85719 1623171717538 1.21838 1.21840 6
my question is: How can I launch the application and see the live update of the graph?
this is not the best version, but it allows you to clearly see how it works
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.graph_objs as go
import sqlite3
import pytz
import pandas as pd
import numpy as np
from datetime import datetime
app = dash.Dash(__name__)
points = 0
def test():
global points
points += 1
def get_value(n_intervals):
timezone = pytz.timezone("Etc/UTC")
utc_from = datetime(2021, 3, 23, tzinfo=timezone)
base = sqlite3.connect('base_eurousd.db')
cur = base.cursor()
read_db = cur.execute('SELECT * FROM data_eurusd').fetchall()
df = pd.DataFrame(read_db)
# d = pd.read_sql("select * from data", db_conn)
df[0] = pd.to_datetime(df[0], unit='ms')
df[3] = np.where(df[1].diff().lt(0) | df[2].diff().lt(0), df[3] * -1, df[3])
#print(df)
return df
def serve_layout():
return html.Div(
children=[
html.H4(children='Доска'),
html.Div(id='my-id', children='''EURUSD'''),
dcc.Graph(id='example-graph', animate=True, responsive=True),
dcc.Interval(
id='interval-component',
interval=3 * 1000,
n_intervals=0,
),
],
)
app.layout = serve_layout
#app.callback(
Output('example-graph','figure'),
[Input('interval-component', 'n_intervals')])
def update_graph(n_intervals):
df = get_value(n_intervals)
test()
return \
{
'data': [
{'x': df[0], 'y': df[1], 'type': 'line', 'name': 'BID'},
{'x': df[0], 'y': df[2], 'type': 'line', 'name': 'ASK'},
],
'layout': go.Layout(xaxis=dict(range=[min(df[0]),max(df[0])]),yaxis=dict(range=[min(df[1]),max(df[2])]),)
}
if __name__ == '__main__':
app.run_server(debug=True)
Related
I'm developing my first Dash Plotly metrics dashboard. That stated, I was able to get most of the dashboard dark themed except the area around my plotly graph object. See below:
How can I get the area around my graph the same dark theme as the rest of the dashboard?
Below is the code I used to materialize the dashboard.
import dash
from dash import Dash, dcc, dash_table
import dash_bootstrap_components as dbc
import dash_design_kit as ddk
from dash import html
import plotly.express as px
import plotly.graph_objects as go
import plotly.io as pio
from google.cloud import bigquery
import pandas as pd
import numpy as np
import os
from google.oauth2 import service_account
df = query_job.to_dataframe()
df['dmand_month'] = pd.to_datetime(df['dmand_yr_mo']).dt.month
df.loc[:, 'price'] = df.loc[:, 'sales_dollars']/df.loc[:, 'ord_qty']
df.loc[:, 'predicted_sales'] = np.round(df.loc[:, 'predictions']*df.loc[:, 'price'])
df.loc[:, 'diff'] = np.round(np.abs(np.round(df.loc[:, 'predicted_sales'] - df.loc[:, 'sales_dollars'],2)))
#BUSINESS LINE
bl = df.groupby(['location_type', 'GLBL_BUS_LN_DESC']).agg({'ord_qty':'sum',
'predictions':'sum',
'sales_dollars':'sum',
'predicted_sales':'sum',
'diff':'sum'}).reset_index()
bl.replace([np.inf, -np.inf], np.nan, inplace=True)
bl['sales_dollars'] = np.round(bl['sales_dollars'])
bl.dropna(inplace = True)
bl.loc[:, 'MAPE'] = np.round(np.round(bl.loc[:, 'diff']/ bl.loc[:, 'sales_dollars'], 4) * 100,2)
bl.loc[:, 'BIAS'] = np.round(np.round((bl.loc[:,'predicted_sales']- bl.loc[:, 'sales_dollars'])/ bl.loc[:, 'sales_dollars'], 4) * 100,2)
fig1 = go.Figure(data=[
go.Bar( name='MAPE', x=bl['GLBL_BUS_LN_DESC'], y=bl['MAPE']),
go.Bar(name='BIAS', x=bl['GLBL_BUS_LN_DESC'], y=bl['BIAS'])
])
fig1.update_layout(barmode='group', plot_bgcolor='rgb(0,0,0)')
colors = {
'background': '#000000',
'text': '#111111'
}
# initialize app
app = dash.Dash(__name__, external_stylesheets=[dbc.themes.DARKLY])
# set app layout
app.layout = html.Div(children=[
html.H1('Demand Forecasting Model Overview',style={
'textAlign': 'center'}),
html.Div(children='''
Dash: A web application to help assess predictors for furture demand forecasting models.
''', style={
'textAlign': 'center'}),
html.Br(),
dcc.Dropdown(options = [{'label':'home_delivery', 'value':'home_delivery'},
{'label': 'shop_sales', 'value':'shop+sales'}],
id='location-dropdown'),
dcc.Graph(id='Business Line MAPE', figure=fig1),
html.H2(children='Demand Forecast by Business Line', style={
'textAlign': 'center'}),
dash_table.DataTable(
data=bl.to_dict('records'),
columns=[{'id': c, 'name': c} for c in bl.columns],
style_header={
'backgroundColor': 'rgb(30, 30, 30)',
'color': 'white'
},
style_data={
'backgroundColor': 'rgb(50, 50, 50)',
'color': 'white'
},
)
# dcc.Graph(id='Business Line BIAS', figure=fig2),
# dcc.Graph(id='Month', figure=fig_month)
])
if __name__ == '__main__':
app.run_server(debug=True)
You should add paper_bgcolor in your update_layout as below:
fig.update_layout(barmode='group', plot_bgcolor='rgb(0,0,0)',paper_bgcolor='rgb(0,0,0)')
I would like to add a range slider along with my dropdown, and make the range slider the 'Wallclock' datetime along with an interaction that allows the range slider to chose the datetime for that capsules based on the dropdown value. I managed to find several ways that other people have done this but none seems to work for my situation especially the callback and the update of the graph. Thank you!
Data looks like this.
Dash looks like this.
Code looks like this.
import pandas as pd
import plotly.express as px # (version 4.7.0)
import plotly.graph_objects as go
import numpy as np
import openpyxl
import dash # (version 1.12.0) pip install dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
from dash.exceptions import PreventUpdate
app = dash.Dash(__name__)
server = app.server
df = pd.read_excel("tcd vs rh 2.xlsx")
print(df)
capsuleID = df['Capsule_ID'].unique()
print(capsuleID)
capsuleID_names = sorted(list(capsuleID))
print(capsuleID_names)
capsuleID_names_1 = [{'label': k, 'value': k} for k in sorted(capsuleID)]
capsuleID_names_2 = [{'label': '(Select All)', 'value': 'All'}]
capsuleID_names_all = capsuleID_names_1 + capsuleID_names_2
app.layout = html.Div([
html.H1("Relative Humidity vs TCD", style={'text-align': 'center'}),
dcc.Dropdown(id="capsule_select",
options=capsuleID_names_all,
optionHeight=25,
multi=True,
searchable=True,
placeholder='Please select...',
clearable=True,
value=['All'],
style={'width': "100%"}
),
dcc.RangeSlider(id='slider',
min=df['Wallclock'].min(),
max=df['Wallclock'].max(),
value=[df.iloc[-101]['Wallclock'].timestamp(), df.iloc[-1]['Wallclock'].timestamp()]
),
html.Div([
dcc.Graph(id="the_graph"),
]),
])
# -----------------------------------------------------------
#app.callback(
Output('the_graph', 'figure'),
Output('capsule_select', 'value'),
Input('capsule_select', 'value'),
Input('slider', 'value'),
)
def update_graph(capsule_chosen):
lBound = pd.to_datetime(value[0], unit='s')
uBound = pd.to_datetime(value[1], unit='s')
filteredData = df.loc[(df['date'] >= lBound) & (df['date'] <= uBound)]
dropdown_values = capsule_chosen
if "All" in capsule_chosen:
dropdown_values = capsuleID_names
dff = df
else:
dff = df[df['Capsule_ID'].isin(capsule_chosen)] # filter all rows where capsule ID is the capsule ID selected
scatterplot = px.scatter(
data_frame=dff,
x="tcd",
y="humidity",
hover_name="Wallclock",
)
scatterplot.update_traces(textposition='top center')
return scatterplot, dropdown_values
# ------------------------------------------------------------------------------
if __name__ == '__main__':
app.run_server(debug=True)
obviously I don't have access to your Excel spreadsheet so generated a data frame with same shape
taken approach of using a second figure with a rangeslider for slider capability
updated callback to use this figure as input for date range
used jupyter dash inline, this can be changed back to your setup (commented lines)
generate some sample data
import pandas as pd
import numpy as np
df = pd.DataFrame(
{
"Wallclock": pd.date_range(
"22-dec-2020 00:01:36", freq="5min", periods=2000
),
"tcd": np.linspace(3434, 3505, 2000) *np.random.uniform(.9,1.1, 2000),
"humidity": np.linspace(63, 96, 2000),
}
).pipe(lambda d: d.assign(Capsule_ID=(d.index // (len(d)//16))+2100015))
slider is a figure with a rangeslider
import pandas as pd
import plotly.express as px # (version 4.7.0)
import plotly.graph_objects as go
import numpy as np
import openpyxl
import dash # (version 1.12.0) pip install dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
from dash.exceptions import PreventUpdate
from jupyter_dash import JupyterDash
# app = dash.Dash(__name__)
# server = app.server
app = JupyterDash(__name__)
# df = pd.read_excel("tcd vs rh 2.xlsx")
# print(df)
capsuleID = df["Capsule_ID"].unique()
# print(capsuleID)
capsuleID_names = sorted(list(capsuleID))
# print(capsuleID_names)
capsuleID_names_1 = [{"label": k, "value": k} for k in sorted(capsuleID)]
capsuleID_names_2 = [{"label": "(Select All)", "value": "All"}]
capsuleID_names_all = capsuleID_names_1 + capsuleID_names_2
def slider_fig(df):
return px.scatter(
df.groupby("Wallclock", as_index=False).size(), x="Wallclock", y="size"
).update_layout(
xaxis={"rangeslider": {"visible": True}, "title":None},
height=125,
yaxis={"tickmode": "array", "tickvals": [], "title": None},
margin={"l": 0, "r": 0, "t": 0, "b": 0},
)
app.layout = html.Div(
[
html.H1("Relative Humidity vs TCD", style={"text-align": "center"}),
dcc.Dropdown(
id="capsule_select",
options=capsuleID_names_all,
optionHeight=25,
multi=True,
searchable=True,
placeholder="Please select...",
clearable=True,
value=["All"],
style={"width": "100%"},
),
dcc.Graph(
id="slider",
figure=slider_fig(df),
),
html.Div(
[
dcc.Graph(id="the_graph"),
]
),
]
)
# -----------------------------------------------------------
#app.callback(
Output("the_graph", "figure"),
Output("capsule_select", "value"),
Output("slider", "figure"),
Input("capsule_select", "value"),
Input('slider', 'relayoutData'),
State("slider", "figure")
)
def update_graph(capsule_chosen, slider, sfig):
dropdown_values = capsule_chosen
if "All" in capsule_chosen:
dropdown_values = capsuleID_names
dff = df
else:
dff = df[
df["Capsule_ID"].isin(capsule_chosen)
] # filter all rows where capsule ID is the capsule ID selected
if slider and "xaxis.range" in slider.keys():
dff = dff.loc[dff["Wallclock"].between(*slider["xaxis.range"])]
else:
# update slider based on selected capsules
sfig = slider_fig(dff)
scatterplot = px.scatter(
data_frame=dff,
x="tcd",
y="humidity",
hover_name="Wallclock",
)
scatterplot.update_traces(textposition="top center")
return scatterplot, dropdown_values, sfig
# ------------------------------------------------------------------------------
if __name__ == "__main__":
# app.run_server(debug=True)
app.run_server(mode="inline")
I'm having so many issues align my map componants to the left of my data grid componant. I want each componant side by side. I have tried adding Divs, included attibutes and changing style. Please help.
import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_leaflet as dl
import pandas as pd
import numpy as np
import dash_table_experiments as dt
lats = [28.538330, 34.729542, 40.712776]
lons = [-81.378883, -86.585297, -74.005974]
df = pd.DataFrame(columns=["lat", "lon"], data=np.column_stack((lats, lons)))
markers = [dl.Marker(position=[row["lat"], row["lon"]]) for i, row in df.iterrows()]
app = dash.Dash()
app = dash.Dash(external_stylesheets=['https://codepen.io/chriddyp/pen/bWLwgP.css'])
df = pd.read_csv('Foundational Data-LA057.csv')
def generate_table(dataframe, max_rows=10):
return html.Table([
html.Thead(
html.Tr([html.Th(col) for col in dataframe.columns])
),
html.Tbody([
html.Tr([
html.Td(dataframe.iloc[i][col]) for col in dataframe.columns
]) for i in range(min(len(dataframe), max_rows))
])
])
colors = {
'background': '#111111',
'text': '#7FDBFF'
}
app.layout = html.Div([
html.Div(
className="row",
children=[
html.Div([dl.Map(children=[dl.TileLayer(url="https://a.tile.openstreetmap.org/{z}/{x}/{y}.png"), dl.LayerGroup(markers)],
style={'width': "100%", 'height': "100%"}, center=[38.627003, -90.199402], zoom=4, id="map"),
], style={'width': '600px', 'height': '500px'}),
generate_table(df)
]
)
])
if __name__ == '__main__':
app.run_server(debug=True)
I'm trying to hide time gaps in the stock market. My problem is that I don't know how to use rangebreaks correctly in dash. https://plotly.com/python/reference/#layout-xaxis-rangebreaks
https://plotly.com/python/time-series/
app = dash.Dash()
app.layout = html.Div([
dcc.Graph(id='graph'),
dcc.Dropdown(id='chooser',options=companies_options,value='CDPROJEKT')
])
#app.callback(Output('graph', 'figure'),
[Input('chooser', 'value')])
def update_figure(selected_company):
df_by_company = df_full[df_full['Nazwa'] == selected_company]
df_by_company= df_by_company[(df_by_company['date'].dt.hour<17) & (df_by_company['date'].dt.hour>8)]
traces = []
print(df_by_company['date'].unique())
traces.append(go.Scatter(
x=df_by_company['date'],
y=df_by_company['Kurs'],
text=df_by_company['Nazwa'],
mode='markers',
opacity=0.7,
#marker={'size': 15},
name=selected_company
))
return {
'data': traces,
'layout': go.Layout(
xaxis= dict(title= 'Time',rangebreaks=[dict(bounds=[17, 8])]),
yaxis={'title': 'Price' },
hovermode='closest'
)
}
if __name__ == '__main__':
app.run_server()
This is my output graph.
https://prnt.sc/rttbkk
Edit:
When I simplified the code I found a solution for my problem.
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
import pandas as pd
df= pd.read_csv('cdr.csv')
app = dash.Dash()
app.layout = html.Div([dcc.Graph(id='scatterplot',
figure = {'data':[
go.Scatter(
x=df['date'],
y=df['price'],
mode='markers')],
'layout':go.Layout(title='My Scatterplot',
xaxis= dict(title= 'Time', rangebreaks=[{ 'pattern': 'hour', 'bounds': [17.5, 8.5] } ]) )}
)])
if __name__ == '__main__':
app.run_server()
My csv file looks like that:
date,number,price
2020-04-03 17:04:15,8838,297.0
https://prnt.sc/ruyob3
I am attempting to create a dash app for creating a scatter plot of some data.. Would someone be able to give me a tip for showing titles on the x & y axis of the plot? It seems like most documentation I am finding online seems like its for IPython. Layouts are defined in this format:
layout = dict(
title= 'Rank',
ticklen= 5,
gridwidth= 2,
)
But my dash app looks more like this format: EDIT to include all code 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
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([
html.H1('Heating System Temperature Data Visulation'),
html.Center('The purpose of the scatter plot below is to prove if a temperature reset strategy is implemented on the hydronic heating system. At various outside air temperature conditions, the hot water temperature should fluctuate to save energy.'),
dcc.Graph(
id='hwst-vs-oat',
figure={
'data': [
go.Scatter(
x = df.OAT,
y = df.HWST,
mode = 'markers',
marker = dict(
color = '#FFBAD2',
line = dict(width = 1)
)
)
],
'layout':{
'title':'Scatter Plot of OAT versus HWST',
'xaxis':{
'title':'whatever you want x to be'
},
'yaxis':{
'title':'whatever you want y to be'
}
}
)
])
if __name__ == '__main__':
app.run_server(debug=True)
Any tips help thank you.
should be able to do something like this
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 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([
html.H1('Heating System Temperature Data Visulation'),
html.Center('The purpose of the scatter plot below is to prove if a temperature reset strategy is implemented on the hydronic heating system. At various outside air temperature conditions, the hot water temperature should fluctuate to save energy.'),
dcc.Graph(
id='hwst-vs-oat',
figure={
'data': [
go.Scatter(
x = df.OAT,
y = df.HWST,
mode = 'markers',
marker = dict(
color = '#FFBAD2',
line = dict(width = 1)
)
)
],
'layout':{
'title':'Scatter Plot of OAT versus HWST',
'xaxis':{
'title':'whatever you want x to be'
},
'yaxis':{
'title':'whatever you want y to be'
}
}
}
)
])
if __name__ == '__main__':
app.run_server(debug=True)