0
votes

I am using plotly express and dash to create my first live interactive dashboard. The current display is very basic just 2 graphs and a checkbox list for province. My next addition was going to be a date range picker from dash core components. However I cannot seem to integrate this piece successfully into the callback.

I also cannot seem to find any examples online of callbacks with multiple inputs that are using the date range picker.

My code is below, any suggestions or feedback is appreciated.

import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px
import pandas as pd
import datetime
from dash.dependencies import Input, Output

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

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

# assume you have a "long-form" data frame
# see https://plotly.com/python/px-arguments/ for more options

df = pd.read_csv(r'DashboardInfo.csv', header=None, names= ['ACR ID',
                                                                                        'Agent ID',
                                                                                        'Agency Code',
                                                                                        'Agreement ID',
                                                                                        'Unit Total',
                                                                                        'TXN Date',
                                                                                        'Product Code',
                                                                                        'Original Unit Quantity',
                                                                                        'Current Unit Quantity',
                                                                                        'Is Escalator',
                                                                                        'Escalator Percentage',
                                                                                        'Primary Sub ID',
                                                                                        'Sub Birthdate',
                                                                                        'Sub Gender',
                                                                                        'Residential ID',
                                                                                        'Province',
                                                                                        'City',
                                                                                        'Postal Code',
                                                                                        'Address 1',
                                                                                        'Address 2',
                                                                                        'Agent Name',
                                                                                        'Branch'])


today_date = datetime.datetime.today().strftime('%Y%m%d')

df['TXN Date'] = pd.to_datetime(df['TXN Date'])
print(df['TXN Date'])
#df.set_index('TXN Date',inplace=True)

print(df.dtypes)

app.layout = html.Div(children=[
    html.H1(children='Sales Results Dashboard'),

    html.Div(children='''
        Sales Rep Production for 
    ''' + today_date),

    dcc.Graph(
        id='example-graph',
    ),
    
    dcc.Graph(
        id='branch-graph',
    ),
    
    #plan type checklist
    html.Label('Checkboxes'),
    dcc.Checklist(
        id='Plan_Type_Checklist',
        options=[
                {'label': x, 'value': x, 'disabled': False}
                for x in df['Province'].unique()
        ],
        value=['BC','AB','SK','MB','ON','QC','NB','NL','PE','NS']
    ),
    
    html.Label('Date Picker Range'),
    dcc.DatePickerRange(
    id = 'Date Picker Range',
    clearable = True,
    start_date=df['TXN Date'].iloc[0],
    end_date=df['TXN Date'].iloc[-1]
    #min_date_allowed=datetime(2018,1,1)
    ),
    
])


@app.callback([
    Output(component_id = 'example-graph',component_property ='figure'),
    Output(component_id = 'branch-graph',component_property ='figure')],
    [Input(component_id = 'Plan_Type_Checklist', 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(options_chosen, start_date, end_date):
#options chosen links to component properter = 'value'

    df_modified_chart = df[(df['TXN Date'] > start_date) & (df['TXN Date'] < end_date)(df['Province'].isin(options_chosen))].groupby(by=['Agent Name'],as_index=False)['Unit Total'].sum()#['TXN Date']
    #df_modified_chart.set_index('TXN Date', inplace=True)
    print(df_modified_chart.head())
    print('df_modified_chart head printed above')
    df_modified_chart2 = df[(df['Province'].isin(options_chosen))].groupby(by=['Branch'],as_index=False)['Unit Total'].sum().loc[start_date:end_date]
    print(df_modified_chart2.dtypes)
    
    fig = px.bar(
            df_modified_chart, 
            x="Agent Name", 
            y="Unit Total",
            ).update_xaxes(categoryorder='total descending')
    
    fig2 = px.bar(
            df_modified_chart2, 
            x="Branch", 
            y="Unit Total"
            ).update_xaxes(categoryorder='total descending')

    return fig, fig2
    

if __name__ == '__main__':
    app.run_server(debug=True)
1
what's the error that you're getting? - Adam Schroeder

1 Answers

0
votes

Figured out I was messing up the dataframe setup in the callback. Revised code below:

The line that was giving me trouble is below:

 df_modified_chart = df[(df['TXN Date'] > start_date) & (df['TXN Date'] < end_date) & (df['Province'].isin(options_chosen))].groupby(by=['Agent Name'],as_index=False)['Unit Total'].sum()

Complete revised code below:

# -*- coding: utf-8 -*-

# Run this app with `python app.py` and
# visit http://127.0.0.1:8050/ in your web browser.

import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px
import pandas as pd
import datetime
from dash.dependencies import Input, Output

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

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

# assume you have a "long-form" data frame
# see https://plotly.com/python/px-arguments/ for more options

df = pd.read_csv(r'DashboardInfo.csv', header=None, names= ['ACR ID',
                                                                                        'Agent ID',
                                                                                        'Agency Code',
                                                                                        'Agreement ID',
                                                                                        'Unit Total',
                                                                                        'TXN Date',
                                                                                        'Product Code',
                                                                                        'Original Unit Quantity',
                                                                                        'Current Unit Quantity',
                                                                                        'Is Escalator',
                                                                                        'Escalator Percentage',
                                                                                        'Primary Sub ID',
                                                                                        'Sub Birthdate',
                                                                                        'Sub Gender',
                                                                                        'Residential ID',
                                                                                        'Province',
                                                                                        'City',
                                                                                        'Postal Code',
                                                                                        'Address 1',
                                                                                        'Address 2',
                                                                                        'Agent Name',
                                                                                        'Branch'])


today_date = datetime.datetime.today().strftime('%Y%m%d')

df['TXN Date'] = pd.to_datetime(df['TXN Date'])
print(df['TXN Date'])
#df.set_index('TXN Date',inplace=True)

print(df.dtypes)

app.layout = html.Div(children=[
    html.H1(children='Sales Results Dashboard'),

    html.Div(children='''
        Sales Rep Production for 
    ''' + today_date),

    dcc.Graph(
        id='example-graph',
    ),
    
    dcc.Graph(
        id='branch-graph',
    ),
    
    #plan type checklist
    html.Label('Checkboxes'),
    dcc.Checklist(
        id='Plan_Type_Checklist',
        options=[
                {'label': x, 'value': x, 'disabled': False}
                for x in df['Province'].unique()
        ],
        value=['BC','AB','SK','MB','ON','QC','NB','NL','PE','NS']
    ),
    
    html.Label('Date Picker Range'),
    dcc.DatePickerRange(
    id = 'Date Picker Range',
    clearable = True,
    start_date=df['TXN Date'].iloc[0],
    end_date=df['TXN Date'].iloc[-1]
    #min_date_allowed=datetime(2018,1,1)
    ),
    
     # Map
    html.Div([
    dcc.Graph(id='graph', config={'displayModeBar': False, 'scrollZoom': True},
    style={'background':'#00FC87','padding-bottom':'2px','padding-left':'2px','height':'100vh'}
    )
    ], className='nine columns'
    ),
    
])


@app.callback([
    Output(component_id = 'example-graph',component_property ='figure'),
    Output(component_id = 'branch-graph',component_property ='figure')],
    [Input(component_id = 'Plan_Type_Checklist', 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(options_chosen, start_date, end_date):
#options chosen links to component properter = 'value'

    df_modified_chart = df[(df['TXN Date'] > start_date) & (df['TXN Date'] < end_date) & (df['Province'].isin(options_chosen))].groupby(by=['Agent Name'],as_index=False)['Unit Total'].sum()#['TXN Date']
    #df_modified_chart.set_index('TXN Date', inplace=True)
    print(df_modified_chart.head())
    print('df_modified_chart head printed above')
    df_modified_chart2 = df[(df['Province'].isin(options_chosen))].groupby(by=['Branch'],as_index=False)['Unit Total'].sum().loc[start_date:end_date]
    print(df_modified_chart2.dtypes)
    
    fig = px.bar(
            df_modified_chart, 
            x="Agent Name", 
            y="Unit Total",
            ).update_xaxes(categoryorder='total descending')
    
    fig2 = px.bar(
            df_modified_chart2, 
            x="Branch", 
            y="Unit Total"
            ).update_xaxes(categoryorder='total descending')

    return fig, fig2
    

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