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

发布于 2025-02-12 01:59:54 字数 5300 浏览 3 评论 0原文

我一直在尝试使用 @app.callback函数在Python中创建一个交互式仪表板。我的数据集布局可以汇总到4个主列中。

“

我希望地理和时间段以下拉序列的形式表现出来(因此使用DCC。下拉函数。下拉函数。第一个下拉列表将根据地理过滤数据集,第二个下拉列表将在该国内定义“时期时间-MAT,L12W或L4W)。因此,以某种方式将第二个下拉列表集成在第一个下拉列表中。

我熟悉这两者都熟悉下拉词和 @app.callback函数,但我似乎找不到同时关键的脚本。我猜测的地理位置和时间段。但是,我尝试了所有内容

。从“ #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()

I have been trying to create an interactive dashboard in Python using the @app.callback function with two inputs. My dataset layout can be summarized into 4 main columns.

Image

I'd like Geography and Time Period to manifest in the form of dropdowns (therefore use the Dcc. dropdown function. The first dropdown will filter the dataset according to the Geography and the second one will define the "Period time - MAT, L12w or L4w) within the country. Therefore somehow the second dropdown is to be integrated within the first dropdown.

I am familiarized with both the dropdown and @app.callback function. But I can't seem to find a script that fuses both. Important note: the output desired is a pie chart that distinguishes Manufacturers' (Column 2) value share (column 4) according to the selected Geography and time Period. I am guessing the mystery resides in the app.layout structure. However, I tried everything and the code won't work.

Also, you will find the code I have done so far attached. The important bit is from "#DESIGN APP LAYOUT" onwards.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

从来不烧饼 2025-02-19 01:59:54

#Design应用程序布局#################################################### ##################################


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

#DESIGN APP LAYOUT##############################################################################


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()```
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文