在破折号中,选择单选按钮时如何使用回调来更新图形?

时间:2019-03-31 22:16:02

标签: python pandas dataframe plotly-dash plotly-python

我是破折号的新手,在查找有关在回调中使用数据帧的示例时遇到了问题。我创建了一个每周单选按钮和一个每月单选按钮。

选择每月单选按钮后,我希望图形从df_monthly中提取数据,其中每个小节将是每月的工资额。选中每周单选按钮后,我希望图表每周填充一次,这是数据框中的每一行,因为我每周获得一次付款。

我不确定我要去哪里,但我不断收到错误消息,说明TypeError: update_fig() takes 0 positional arguments but 1 was given

图形填充时没有如下图所示的数据。感谢您对此事的帮助。

enter image description here

import dash
import dash_core_components as dcc 
import dash_html_components as html 
import plotly.plotly as py
import plotly.graph_objs as go
import sqlite3
import pandas as pd
from functools import reduce
import datetime

conn = sqlite3.connect('paychecks.db')

df_ct = pd.read_sql('SELECT * FROM CheckTotal',conn)
df_earn = pd.read_sql('SELECT * FROM Earnings', conn)
df_whold = pd.read_sql('SELECT * FROM Withholdings', conn)

data_frames = [df_ct, df_earn, df_whold]
df_paystub = reduce(lambda  left,right: pd.merge(left,right,on=['Date'], how='outer'), data_frames)

def date_extraction(df):
    df['Date'] = pd.to_datetime(df['Date'])
    df['Year'] = df['Date'].dt.strftime('%Y')
    df['Month'] = df['Date'].dt.strftime('%B')
    df['Day'] = df['Date'].dt.strftime('%d')
    return df

date_extraction(df_paystub)

df_monthly = df_paystub.groupby(['Month']).sum()

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

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

app.css.append_css({'external_url': 'https://codepen.io/amyoshino/pen/jzXypZ.css'})

app.layout = html.Div(children=[

    html.Div([
        html.Div([
            dcc.RadioItems(
                        id='data-view',
                        options=[
                            {'label': 'Weekly', 'value': 'Weekly'},
                            {'label': 'Monthly', 'value': 'Monthly'},
                        ],
                        value='',
                        labelStyle={'display': 'inline-block'}
                    ),
        ], className = 'two columns'),

        html.Div([    
            dcc.Dropdown(
                id='year-dropdown',
                options=[
                        {'label': i, 'value': i} for i in df_paystub['Year'].unique()
                ],
                placeholder="Select a year",
            ),
        ], className='five columns'),

        html.Div([    
            dcc.Dropdown(
                id='month-dropdown',
                options=[
                  {'label': i, 'value': i} for i in df_paystub['Month'].unique()
                ],
                placeholder="Select a month(s)",
                multi=True,
            ),
        ], className='five columns'),
    ], className  = 'row'),


    # HTML ROW CREATED IN DASH
    html.Div([
        # HTML COLUMN CREATED IN DASH
        html.Div([
            # PLOTLY BAR GRAPH        
            dcc.Graph(
                id='pay',
            )
        ], className  = 'six columns'),

        # HTML COLUMN CREATED IN DASH
        html.Div([
            # PLOTLY LINE GRAPH
            dcc.Graph(
                id='hours',
                figure={
                    'data': [
                        go.Scatter(
                            x = df_earn['Date'],
                            y = df_earn['RegHours'],
                            mode = 'lines',
                            name = 'Regular Hours',
                        ),
                        go.Scatter(
                            x = df_earn['Date'],
                            y = df_earn['OtHours'],
                            mode = 'lines',
                            name = 'Overtime Hours',
                        )
                    ]
                }
            )
        ], className='six columns')
    ], className='row')
], className='ten columns offset-by-one')

@app.callback(dash.dependencies.Output('pay', 'figure'),
              [dash.dependencies.Input('data-view', 'value')])

def update_fig():
    figure={
        'data': [
            go.Bar(
                x = df_monthly['Month'],
                y = df_monthly['CheckTotal'],
                name = 'Take Home Pay',
            ),
                go.Bar(
                x = df_monthly['Month'],
                y = df_monthly['EarnTotal'],
                name = 'Earnings',
            )
        ],
        'layout': go.Layout(
            title = 'Take Home Pay vs. Earnings',
            barmode = 'group',
            yaxis = dict(title = 'Pay (U.S. Dollars)'),
            xaxis = dict(title = 'Date Paid')
        )
    }
    return figure

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

1 个答案:

答案 0 :(得分:0)

您好@ prime90,欢迎来到Dash。

浏览回调签名时,看起来update_fig()函数需要使用您给定的Input(使用dash.dependencies.Input)。

回调函数将向此Input发送您指定的应用程序中的更改。因此,它将沿着您赋予函数value的{​​{1}}的{​​{1}}发送,该函数目前不接受任何变量,从而导致错误消息。

只需更新函数签名并添加几个布尔变量即可摆脱错误并获得潜在的功能:

#data-view

就像上面的注释中所写的那样,您需要进行某种类型的事前操作来创建df_weekly,就像您当前的df_monthly一样。

此外,我编写的代码段假定df列的名称分别为“ Week”和“ Month”-显然可以根据需要进行更新。

Dash中的数据操作:

确保您阅读了data sharing docs,因为它们突出显示了绝不应该超出范围修改数据

我希望这会有所帮助:-)