0

我正在使用 plotly express 和 dash 创建我的第一个实时交互式仪表板。当前显示非常基本,只有 2 个图表和一个省的复选框列表。我的下一个添加将是来自 dash 核心组件的日期范围选择器。但是我似乎无法将这部分成功集成到回调中。

我似乎也无法在网上找到任何使用日期范围选择器的具有多个输入的回调示例。

我的代码如下,任何建议或反馈表示赞赏。

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)
4

1 回答 1

0

发现我弄乱了回调中的数据框设置。修改后的代码如下:

给我带来麻烦的行如下:

 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()

下面完成修改后的代码:

# -*- 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)
于 2020-09-12T17:50:44.103 回答