如何使用 @app.callback 函数将两个输入作为下拉列表?

问题描述 投票:0回答:1

我一直在尝试使用带有两个输入的 @app.callback 函数在 Python 中创建交互式仪表板。我的数据集布局可以概括为 4 个主要列。

Image

我希望 Geography 和 Time Period 以下拉列表的形式出现(因此使用 Dcc.dropdown 函数。第一个下拉列表将根据 Geography 过滤数据集,第二个将定义“Period time - MAT, L12w或 L4w) 在国内。因此,第二个下拉列表将以某种方式集成到第一个下拉列表中。

我熟悉下拉菜单和@app.callback 函数。但我似乎无法找到融合两者的脚本。重要说明:所需的输出是一个饼图,根据选定的地理和时间段区分制造商(第 2 列)的价值份额(第 4 列)。我猜谜团在于 app.layout 结构。然而,我什么都试过了,代码还是不行。

此外,您会发现我到目前为止所做的代码已附上。重要的一点是从“#DESIGN APP LAYOUT”开始。

import dash
from dash import html
from dash import dcc
from dash.dependencies import Input, Output, State
import plotly.express as px
import pandas as pd
import pandas as pd
pd.options.display.max_columns = None
pd.options.display.max_rows = None
pd.options.display.width=None


data =  pd.read_csv (r'C:\Users\Sara.Munoz\OneDrive - Unilever\Documents\Sarita.csv', 
                            encoding = "ISO-8859-1",
                            )
df=data
print(df.head())
cols=df.columns
print(cols)

###RE-ARRANGE DATASET###
df = pd.melt(df, id_vars=['Geography Node Name', 'Geography Id', 'Geography Level',
       'Category Node Name', 'Category Id', 'Category Level',
       'Global Manufacturer Name', 'Global Manufacturer Id',
       'Brand Position Type', 'Brand Position Name', 'Brand Position Id',
       'Local Brand Name', 'Local Brand Id', 'Measure',
       'Currency or Unit of Measure','Latest Available Date'],value_vars=['MAT','L12W','L4W'], var_name='Period',value_name='Data')

for col in df.columns:
    print(col)


###CLEAN DATASET###

df.rename(columns = {'Geography Node Name':'Geography','Category Node Name':'Category',
                     'Global Manufacturer Name':'Manufacturer','Geography Level':'GLevel'},inplace = True)


df.drop(["Geography Id", "Category Id","Global Manufacturer Id","Brand Position Type",
                  "Brand Position Name","Brand Position Id","Local Brand Name","Local Brand Id","Latest Available Date",
         "Currency or Unit of Measure"], axis = 1, inplace=True)

print("SEE BELOW NEW DATASET")

print(df.head())

#####FOR VALUE SHARE

print("FOR VALUE SHARE")

df2 = df.loc[df['GLevel'] == 5]
df2 = df2.loc[df2['Measure'] == 'Value Share']
df2 = df2.loc[df2['Category'] == 'Toothpaste']
df2 = df2[df2.Manufacturer != 'ALL MANUFACTURERS']
df2 = df2[df2.Category != 'Oral Care']
df2.drop(["GLevel", "Category","Category Level"], axis = 1, inplace=True)
print(df2.head())

#####FOR VOLUME SHARE

print("FOR VOLUME SHARE")

df3 = df.loc[df['GLevel'] == 5]
df3 = df3.loc[df3['Measure'] == 'Volume Share']
df3 = df3.loc[df3['Category'] == 'Toothpaste']
df3 = df3[df3.Manufacturer != 'ALL MANUFACTURERS']
df3 = df3[df3.Category != 'Oral Care']
df3.drop(["GLevel", "Category","Category Level"], axis = 1, inplace=True)
df3=df3.sort_values(['Geography', 'Period'],ascending = [True, True])
df3 = pd.DataFrame(df3)
df3=df3[['Geography','Period','Manufacturer','Measure','Data']]
print(df3)

###############################################################################

app = dash.Dash(__name__)

app.layout = html.Div(
    [
        dcc.Dropdown(
            id="dropdown-1",
            options=[
                             {'label': 'Indonesia', 'value': 'Indonesia'},
                            {'label': 'France', 'value': 'France'},
                             {'label': 'Vietnam', 'value': 'Vietnam'},
                             {'label': 'Chile', 'value': 'Chile'},
                            {'label': 'United Arab Emirates', 'value': 'United Arab Emirates'},
                             {'label': 'Morocco', 'value': 'Morocco'},
                             {'label': 'Russian Federation', 'value': 'Russian Federation'},
                            {'label': 'China', 'value': 'China'},
                             {'label': 'Greece', 'value': 'Greece'},
                             {'label': 'Netherlands', 'value': 'Netherlands'},
                            {'label': 'Austria', 'value': 'Austria'},
                             {'label': 'Germany', 'value': 'Germany'},
                             {'label': 'Switzerland', 'value': 'Switzerland'},
                            {'label': 'Italy', 'value': 'Italy'},
                             {'label': 'Denmark', 'value': 'Denmark'},
                             {'label': 'Norway', 'value': 'Norway'},
                             {'label': 'Sweden', 'value': 'Sweden'}
        ],
            multi=True,
        ),
        dcc.Dropdown(
            id="dropdown-2",
           options=[
                             {'label': 'MAT', 'value': 'MAT'},
                            {'label': 'L12W', 'value': 'L12W'},
                             {'label': 'L4W', 'value': 'L4W'}
        ],
            multi=True,
        ),
        html.Div([], id="plot1", children=[])
    ], style={'display': 'flex'})


@app.callback(
    Output("plot1", "children"),
    [Input("dropdown-1", "value"), Input("dropdown-2", "value")],
    prevent_initial_call=True
)

def get_graph(entered_Geo, entered_Period):
    
    fd = df2[(df3['Geography']==entered_Geo) &
             (df3['Period']==entered_Period)]

    g1= fd.groupby(['Manufacturer'],as_index=False). \
            mean()
    g1 = g1
    plot1= px.pie(g1, values='Data', names='Manufacturer', title="Value MS")


    return[dcc.Graph(figure=plot1)]

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

python callback
1个回答
0
投票

#设计应用布局########################################### #################################


app.layout = html.Div([
    html.Label("Geography:",style={'fontSize':30, 'textAlign':'center'}),
    dcc.Dropdown(
        id='dropdown1',
        options=[{'label': s, 'value': s} for s in sorted(df3.Geography.unique())],
        value=None,
        clearable=False
    ),
    html.Label("Period:", style={'fontSize':30, 'textAlign':'center'}),
    dcc.Dropdown(id='dropdown2',
                 options=[],
                 value=[],
                 multi=False),
    html.Div([
                
                        html.Div([ ], id='plot1'),
                        html.Div([ ], id='plot2')

                        
                    ], style={'display': 'flex'}),


    ])

##############
# Populate the Period dropdown with options and values
@app.callback(
    Output('dropdown2', 'options'),
    Output('dropdown2', 'value'),
    Input('dropdown1', 'value'),
)
def set_period_options(chosen_Geo):
    dff = df3[df3.Geography==chosen_Geo]
    Periods = [{'label': s, 'value': s} for s in df3.Period.unique()]
    values_selected = [x['value'] for x in Periods]
    return Periods, values_selected

# Create graph component and populate with pie chart
@app.callback([Output(component_id='plot1', component_property='children'),
               Output(component_id='plot2', component_property='children')],
              Input('dropdown2', 'value'),
              Input('dropdown1', 'value'),
    prevent_initial_call=True
)
def update_graph(selected_Period, selected_Geo):
    if len(selected_Period) == 0:
        return no_update

    else:
        #Volume Share
        dff3 = df3[(df3.Geography==selected_Geo) & (df3.Period==selected_Period)]
        #Value Share
        dff2 = df2[(df2.Geography==selected_Geo) & (df2.Period==selected_Period)]
        #####

        fig1 = px.pie(dff2, values='Data', names='Manufacturer', title=" Value MS")
        fig2 = px.pie(dff3, values='Data', names='Manufacturer', title=" Volume MS")
        table = 
        
        return [dcc.Graph(figure=fig1),
            dcc.Graph(figure=fig2) ]

if __name__ == '__main__':
    app.run_server()```
© www.soinside.com 2019 - 2024. All rights reserved.