当前位置: 首页 > 知识库问答 >
问题:

使用dcc.datepickerage在Plotly Express中进行多输入回调

姜嘉赐
2023-03-14

我正在使用plotly express和dash创建我的第一个实时交互式仪表板。当前显示非常基本,只有两个图形和一个省的复选框列表。我的下一个新产品是dash core components的日期范围选择器。然而,我似乎无法成功地将这篇文章集成到回调中。

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

我的代码如下,任何建议或反馈都将不胜感激。

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个答案

乜思淼
2023-03-14

我发现我把回调中的数据帧设置搞砸了。修订代码如下:

给我带来麻烦的线路如下:

 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)
 类似资料:
  • 问题内容: 在Python中,该模块可用于在一系列值上并行运行函数。例如,这将生成f的前100000个评估的列表。 当f接受多个输入而只有一个变量变化时,是否可以做类似的事情?例如,如何并行处理此: 问题答案: 有几种方法可以做到这一点。在问题给出的示例中,您可以定义一个包装函数 然后将此包装传递给。一种更通用的方法是使用一个包装器,该包装器使用一个元组参数并将该元组解包为多个参数 或使用等效的l

  • 问题内容: 我有以下形式的文本输入: 我试图让它接受多行输入。宽度和高度会使框变大,但用户可以输入所有想要的文本,但它只能填充一行。 如何使输入更像文本区域? 问题答案: 您需要使用文本区域进行多行处理。

  • 问题内容: 使用Elasticsearch完成建议程序时,我在返回与一词查询匹配的多词输入建议时遇到问题。 示例结构: 工作查询: 结果 查询失败: 结果 我希望得到与工作查询相同的结果,匹配“猫狗”。有什么建议是什么问题,以及如何使失败的查询正常工作?当使用标准分析器而不是空白分析器时,我得到相同的结果。我想每个输入字符串使用多个单词,如上面的示例所示。 问题答案: 完成建议器是前缀建议器,这意

  • 问题内容: 我想知道如何编写一个可以接受多行输入的简单程序,然后可以像在lynx浏览器中一样提交输入,在该浏览器中您可以使用空白行然后使用句点来提交输入。 我想在电子邮件程序中使用它。 问题答案: 这是一个简单的方法:

  • 我正在通过函数验证用户输入。 这是我的代码: 我需要验证用户提供的和的值,以确保它们都是0或更大且不为空。不应接受负值或除数字以外的任何内容。 验证代码应该在get\u double函数中,我似乎不知道如何验证驻留在单独函数中的内容。请寻求指导。

  • 我正在编写一个程序,将给定的整数简化为它们的最简单的比率。但是当通过Scanner类在一个子方法中获取输入时发生了一个错误。下面是代码: