Eric Stralsund
Eric Stralsund

Reputation: 559

Dash Plotly Dashboard Update Dashboard Button

Here is a smaller Version of my Dashboard, the real one has multiple tabs etc. The Dashboard creates all charts from 4 files

Sometimes these files can change their content (name is same but values are different), i need a dashboard update, so that all these files are new loaded an the dashboard runs again, i created a dashboard-update button, but how to realize this?

import dash
import dash_html_components as html
import dash_core_components as dcc
from dash.dependencies import Input, Output, State
import plotly.graph_objs as go
from plotly import tools
import pandas as pd
import datetime
import plotly.tools
from plotly.subplots import make_subplots
import numpy as np

import plotly.io as pio
import sys

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']


dfresult = pd.read_csv("result.csv", sep=",")
dfradar =  pd.read_csv("radar.csv", sep=",")
dfoutput = pd.read_csv("output.csv", sep=",")
dfavg = pd.read_csv("avg_input.csv",sep=",")


#avg_input.csv
dfavg = round(dfavg,2)
avgtable = dfresult.drop(["Feed 1", "Feed 2","Sum Feed In", "Wind 4600","Solar 1900","Holiday", "Sun 2300",  "Total Feed In"],axis=1)
avgtable = avgtable.iloc[1:]
avgtable = round(avgtable.groupby("Date").mean(),2)
avgtable.reset_index( level=None, drop=False, inplace=True, col_level=2, col_fill='')


print(avgtable)

#radar.csv
dfradar = round(dfradar,2)

#output.csv
dfoutput= round(dfoutput,2)
dfoutput= dfoutput.fillna(0)
#result.csv
dfresult
dfresult.fillna(0)
#dfresult["Temperature"] = pd.to_numeric(dfresult["Temperature"])
#dfresavg = round(dfresavg,2)
#create new dataframe: grouped result table by date, calculate mean of consumption and round by two decimals
dfb = pd.DataFrame(round(dfresult.groupby("Date")["Consumption"].mean(),2))
#sort dataframe by date
dfb = dfb.sort_values("Date",ascending=False)
#split dataframe into first row and other rows
first= dfb.iloc[:1]
others = dfb.iloc[1:]
#sort all rows exept first row by consumption from high to low
others = others.sort_values("Consumption",ascending=False)
#create new Dataframe by concatinating first and others (both are Dataframes)
dfbar1 = pd.concat([first,others])

#reset index of Dataframe, replace Column and fill automaticly
dfbar1.reset_index( level=None, drop=False, inplace=True, col_level=2, col_fill='')
dfbar1.Date = dfbar1.Date.astype(str)
dfresult = dfresult.iloc[1:]



app = dash.Dash(__name__)#, external_stylesheets=external_stylesheets)
server = app.server
app.config.suppress_callback_exceptions = True
app.scripts.config.serve_locally = True




###################################################
#demand subplots
###################################################


figd = tools.make_subplots(
    rows=2, cols=2, print_grid=True,
    specs=[[{"type": "xy"}, {"type": "xy"}],[{"type": "xy"}, {"type": "polar"}]],
    subplot_titles=("A", "B", "C", "D"))

c = ["#67c2dc","#16336d","#ffbb0e","#213939","#cc66ff"]
c1 = ["#ffff01","#67c2dc","#16336d","#ffbb0e","#213939","#cc66ff"]

#check order of daylist from dfbar1
daylist = dfbar1.Date.unique()
daylist_small = daylist[1:]


#dfresult.sort_values(["Date","daylist"])

daylistresult = dfresult.Date.unique()

###Chart1
for i,j,a in zip(daylist,dfbar1["Consumption"],range(len(dfbar1.Date))):
    
    figd.append_trace(
        go.Bar(
           x=[i],
           y=[j],
           #name = dfbar1.Date,
           name=str(i),
           legendgroup='group'+str(i),
           showlegend=True,
           marker=dict(color=c1[a]),
    
       
            ),1,1
         ),
figd.update_xaxes(type = 'category')
###Chart2
for i,j in zip(daylist_small,range(len(dfresult.Date.unique()))):
    data = dfresult.loc[dfresult.Date == str(i)]
    
    figd.append_trace(
         go.Scatter(
            x=data["Time"],
            y=data["Consumption"],
            #name=str(data["Date"].unique())[2:-2],
            legendgroup='group'+str(i),
            showlegend=False,
            marker=dict(color=c[j]),
            mode="lines+markers"
            ),1,2
         ),

    
###Chart4
for i,j,a in zip(daylist,dfoutput["Consumption"],range(len(dfoutput.Date))):
    
    figd.append_trace(
        go.Bar(
           x=[i],
           y=[j],
           
           #name=str(i),
           legendgroup='group'+str(i),
           showlegend=False,
           marker=dict(color=c1[a]),
    
       
            ),2,1
         ),
figd.update_xaxes(type = 'category')


###Chart4
for a, i,j in zip(daylist, dfradar.Date.unique(),range(len(dfradar.Date.unique()))):
    figd.append_trace(go.Scatterpolar(
                        r=dfradar["Total"].loc[dfradar["Date"]==i],
                        theta=dfradar["Parameters"].loc[dfradar["Date"]==i],
                        showlegend=False,
                        legendgroup='group'+str(a),
                        marker=dict(color=c1[j]),
                        line_color = c1[j],
                        mode = "lines+markers",
                        opacity = round(j  * (0.4)+0.2,0),
                        fill ='toself'
                        ),2,2)
    
    figd.update_layout(
          #height=500,
          #width =500,
          autosize=True,
          polar = dict(angularaxis = dict( rotation = 45)
          
          ))
        


#set layout for each graph
figd['layout'].update(height=1100,autosize=True,polar = dict(angularaxis = dict( rotation = 45)))


bgc = "#f7f9ef"
background_color = "#f7f9ef"
graphwidth = "33%"
graphheight = "450px"
formwidth = "170px"
formheight = "30px"


templates = ['ggplot2', 'seaborn', 'simple_white', 'plotly','plotly_white', 'plotly_dark', 'presentation', 'xgridoff', 'ygridoff', 'gridon']


app.layout =html.Div([
            #header container with name, update button and logo
            dcc.Dropdown(id='drop-temp',
                                 style={
                                       
                                        "float":"right",
                                        "display": 'inline-block',
                                        "width": "220px",
                                        
                                        },
                                 
                                    options=[
                                        {'label': str(i), 'value': i} for i in templates]
                                        ,placeholder="Select Chart Template"
                                        ),
                
            html.Button("Update Dashboard",id="update", style={
                                                    "width": "220px",
                                                    "float":"left",
                                                    'display': 'inline-block',
                                                    "background":"#e29820",
                                                    "color":"white",
                                                    "height":"35px"
                                                   }),

    
    
    
    
            html.Div(id="empty-slot1",style={"height":"5px"}),
            dcc.Tabs(id="tabs", value='tab2', 
            children=[

            dcc.Tab(label='Overview', value='tab2', style={"height":"7%","width":"16.6%","background":"#e29820","color":"white"}),
            
            ],style={"background":background_color}
            ),

            html.Div(id='tabs-content'),
                
           
                   
                   ],style={"width":"100%",
                     "background":background_color,
                     })

@app.callback(Output('tabs-content', 'children'),
              [Input('tabs', 'value'),
])
def contents(tab):
    
    if tab == 'tab2':
        return html.Div(
            [
            html.H3('Overview'),
            
            dcc.Graph(id="g1",style={"width":"99%"},
                            figure=figd,
                             ),


            ],
                style={"width":"99%",
                       "background":background_color}
                )


if __name__ == '__main__':
    app.run_server(debug=False)

Picture of Dashboard enter image description here

Upvotes: 1

Views: 3095

Answers (1)

Morris wong
Morris wong

Reputation: 163

You will have to use the dcc.interval component to achieve that, add this component in the app layout and then the corresponding call back for the file update

Here is a great example:

https://community.plot.ly/t/dash-app-not-reading-modified-file-on-refreshing-the-browser/27145/8

And also the documentation:

https://dash.plot.ly/live-updates

Upvotes: 1

Related Questions