Interval with Pandas Dataframe

Hello-

I am new to Dash and Plotly but I am really enjoying the powerful capabilities and simplicity of Dash. So far I have two graphs I am really happy with but now I am trying to make them auto update on a certain schedule. From what I have gathered through google I will need to use interval but I have had no luck finding a good example to help me achieve this goal. I am likely missing something simple but I am hoping that someone will help me along so that I can make my graphs update on a certain interval as the source datasheet changes.

I think the changes I need to make are in the app.callback and subsequent function. Do I need to define the graphs within this function? I have included a snippet from one of the recipes but I am not sure how to make it work with my graphs. Any help is greatly appreciated.

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 datetime





df = pd.read_csv(
    'C:\\Users\\Chase\\Documents\\someFile.csv')

#limites rows to last week
df = df.tail(168)
#generate overall hourly averages
df.averagePerHour = (df.Goals + df.Portal+ df.Profile + df.Summary + df.Challenges + df.Past_Challenges + df.Activity_History + df.Nutrition_Data + df.My_Plan + df.My_Program + df.Videos + df.Classes + df.Events + df.Calendar +  df.Home + df.Devices + df.Manage_Priority + df.Messages +  df.Activity + df.Health_Log + df.Fit_Test + df.Records + df.Support + df.Nutrition)/24
#limits rows to last day
df2 = df.tail(24)
#generates dataframe containing weekly averages
df2= df2.mean().to_frame().T

#print list(df2.Portal)

app = dash.Dash()


app.layout = html.Div(id='myTabs', children=[
    #html.H1(children='Dash Tutorials'),
    dcc.Graph(
		id='TTL Over Time',
		figure={
				'data': [
						{'x': df.Date, 'y': df.averagePerHour, 'type': 'line', 'name': 'Hourly Average'},
						],
				'layout': {
							'title': 'Average TTL Per Hour This Week',
							'showlegend': False
						  }
				},


    ),

dcc.Interval(
        id='my_interval',
        interval=5000, # in milliseconds
        n_intervals=0
    ),
    dcc.Input(id='input', value='Enter something here!', type='text'),
    html.Div(id='output')
    ])

@app.callback(
    Output(component_id='output', component_property='children'),
    [Input(component_id='input', component_property='value')]
)
def update_value(input_data):
    return 'Input: "{}"'.format(input_data)


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

Welcome to Dash!

I highly recommend checking out the official user guide that I wrote here: https://dash.plot.ly/. In “Advanced Usage”, see the “Live Updates” chapter. There is an example within on the dcc.Interval component.

1 Like

Thanks a lot for the help. I was able to use your code as a reference for my own and get it working as expected. Here is the new code, hope it helps someone in the future!

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 datetime



#print list(df2.Portal)

app = dash.Dash(__name__)
app.layout = html.Div(
    html.Div([
        html.H4('Interval Test'),
        dcc.Graph(id='live-update-graph'),
        dcc.Interval(
            id='interval-component',
            interval=1*10000, # in milliseconds
            n_intervals=0
        )
    ])
)

@app.callback(Output('live-update-graph', 'figure'),
              [Input('interval-component', 'n_intervals')])
def update_graph_live(n):
    df = pd.read_csv(
    'C:\\Users\\Chase\\Documents\\someFile.csv')

    #limites rows to last week
    df = df.tail(168)
    #generate overall hourly averages
    df.averagePerHour = (df.Goals + df.Portal+ df.Profile + df.Summary + df.Challenges + df.Past_Challenges + df.Activity_History + df.Nutrition_Data + df.My_Plan + df.My_Program + df.Videos + df.Classes + df.Events + df.Calendar +  df.Home + df.Devices + df.Manage_Priority + df.Messages +  df.Activity + df.Health_Log + df.Fit_Test + df.Records + df.Support + df.Nutrition)/24
    #limits rows to last day
    df2 = df.tail(24)
    #generates dataframe containing weekly averages
    df2= df2.mean().to_frame().T

    # Create the graph with subplots
    fig =   {
                'data': [
                        {'x': df.Date, 'y': df.averagePerHour, 'type': 'line', 'name': 'Hourly Average'},
                        ],
                'layout': {
                            'title': 'Average TTL Per Hour This Week',
                            'showlegend': False
                          }
                }

    return fig



if __name__ == '__main__':
    app.run_server(debug=True)
2 Likes

Hi,
What if we want to do for a graph with multiple graphs.
For example, in the following code, how will we implement n_intervals

app.layout = html.Div([
    html.Div([

        html.Div([
            dcc.Dropdown(
                id='crossfilter-xaxis-column',
                options=[{'label': i, 'value': i} for i in available_indicators],
                value='Fertility rate, total (births per woman)'
            ),
            dcc.RadioItems(
                id='crossfilter-xaxis-type',
                options=[{'label': i, 'value': i} for i in ['Linear', 'Log']],
                value='Linear',
                labelStyle={'display': 'inline-block'}
            )
        ],
        style={'width': '49%', 'display': 'inline-block'}),

        html.Div([
            dcc.Dropdown(
                id='crossfilter-yaxis-column',
                options=[{'label': i, 'value': i} for i in available_indicators],
                value='Life expectancy at birth, total (years)'
            ),
            dcc.RadioItems(
                id='crossfilter-yaxis-type',
                options=[{'label': i, 'value': i} for i in ['Linear', 'Log']],
                value='Linear',
                labelStyle={'display': 'inline-block'}
            )
        ], style={'width': '49%', 'float': 'right', 'display': 'inline-block'})
    ], style={
        'borderBottom': 'thin lightgrey solid',
        'backgroundColor': 'rgb(250, 250, 250)',
        'padding': '10px 5px'
    }),

    html.Div([
        dcc.Graph(
            id='crossfilter-indicator-scatter',
            hoverData={'points': [{'customdata': 'Japan'}]}
        )
    ], style={'width': '49%', 'display': 'inline-block', 'padding': '0 20'}),
    html.Div([
        dcc.Graph(id='x-time-series'),
        dcc.Graph(id='y-time-series'),
    ], style={'display': 'inline-block', 'width': '49%'}),

    html.Div(dcc.Slider(
        id='crossfilter-year--slider',
        min=df['Year'].min(),
        max=df['Year'].max(),
        value=df['Year'].max(),
        marks={str(year): str(year) for year in df['Year'].unique()}
    ), style={'width': '49%', 'padding': '0px 20px 20px 20px'})
])


@app.callback(
    dash.dependencies.Output('crossfilter-indicator-scatter', 'figure'),
    [dash.dependencies.Input('crossfilter-xaxis-column', 'value'),
     dash.dependencies.Input('crossfilter-yaxis-column', 'value'),
     dash.dependencies.Input('crossfilter-xaxis-type', 'value'),
     dash.dependencies.Input('crossfilter-yaxis-type', 'value'),
     dash.dependencies.Input('crossfilter-year--slider', 'value')])
def update_graph(xaxis_column_name, yaxis_column_name,
                 xaxis_type, yaxis_type,
                 year_value):
    dff = df[df['Year'] == year_value]

    return {
        'data': [go.Scatter(
            x=dff[dff['Indicator Name'] == xaxis_column_name]['Value'],
            y=dff[dff['Indicator Name'] == yaxis_column_name]['Value'],
            text=dff[dff['Indicator Name'] == yaxis_column_name]['Country Name'],
            customdata=dff[dff['Indicator Name'] == yaxis_column_name]['Country Name'],
            mode='markers',
            marker={
                'size': 15,
                'opacity': 0.5,
                'line': {'width': 0.5, 'color': 'white'}
            }
        )],
        'layout': go.Layout(
            xaxis={
                'title': xaxis_column_name,
                'type': 'linear' if xaxis_type == 'Linear' else 'log'
            },
            yaxis={
                'title': yaxis_column_name,
                'type': 'linear' if yaxis_type == 'Linear' else 'log'
            },
            margin={'l': 40, 'b': 30, 't': 10, 'r': 0},
            height=450,
            hovermode='closest'
        )
    }


def create_time_series(dff, axis_type, title):
    return {
        'data': [go.Scatter(
            x=dff['Year'],
            y=dff['Value'],
            mode='lines+markers'
        )],
        'layout': {
            'height': 225,
            'margin': {'l': 20, 'b': 30, 'r': 10, 't': 10},
            'annotations': [{
                'x': 0, 'y': 0.85, 'xanchor': 'left', 'yanchor': 'bottom',
                'xref': 'paper', 'yref': 'paper', 'showarrow': False,
                'align': 'left', 'bgcolor': 'rgba(255, 255, 255, 0.5)',
                'text': title
            }],
            'yaxis': {'type': 'linear' if axis_type == 'Linear' else 'log'},
            'xaxis': {'showgrid': False}
        }
    }


@app.callback(
    dash.dependencies.Output('x-time-series', 'figure'),
    [dash.dependencies.Input('crossfilter-indicator-scatter', 'hoverData'),
     dash.dependencies.Input('crossfilter-xaxis-column', 'value'),
     dash.dependencies.Input('crossfilter-xaxis-type', 'value')])
def update_y_timeseries(hoverData, xaxis_column_name, axis_type):
    country_name = hoverData['points'][0]['customdata']
    dff = df[df['Country Name'] == country_name]
    dff = dff[dff['Indicator Name'] == xaxis_column_name]
    title = '<b>{}</b><br>{}'.format(country_name, xaxis_column_name)
    return create_time_series(dff, axis_type, title)


@app.callback(
    dash.dependencies.Output('y-time-series', 'figure'),
    [dash.dependencies.Input('crossfilter-indicator-scatter', 'hoverData'),
     dash.dependencies.Input('crossfilter-yaxis-column', 'value'),
     dash.dependencies.Input('crossfilter-yaxis-type', 'value')])
def update_x_timeseries(hoverData, yaxis_column_name, axis_type):
    dff = df[df['Country Name'] == hoverData['points'][0]['customdata']]
    dff = dff[dff['Indicator Name'] == yaxis_column_name]
    return create_time_series(dff, axis_type, yaxis_column_name)


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