jaae
jaae

Reputation: 13

How to create a pie subplots that takes multiple inputs

I want to build two pie subplots that takes as input the country, the sector and the year. And I want to see the proportions of job positions that mens have, and the proportions of job positions that women have.

(for example for man 'CEo'=23%, President=20%, Member=57%).

And in the same way the pie for womens

This is the code I have done till now


    app=dash.Dash(__name__, meta_tags=[{"name":"viewport","content":"width=device-width"}],
             external_stylesheets=[dbc.themes.BOOTSTRAP])
df=pd.read_csv('report.csv')
#fill NAs with zeros
df=df.fillna(0)

#Create the list to show in dropdown element from a specific dataset column
country = df['geo'].unique()
country = country.tolist()
country.insert(0, 'Select all')
settore = df['NACE'].unique()



app.layout=html.Div([
    
    
    
    html.Div([
        html.H1(children='A gender analysis ',
                style={'textAlign':'center'}),
        html.P(children='A case study of the top company from 2011 al 2023',
              style={'textAlign':'left', 'margin-left':'1%'})
    
    ], style={"margin-bottom": "3vw", 'margin-left':'1%', "border":"2px purple solid", 'background-color':'#FF69B4'}),
    
    
    html.Div([
        "Select the year:",
        dcc.Slider(id='year-slider',
                   included=False,
                   updatemode='drag',
                   tooltip={'always_visible':True},
                   min=2011,
                   max=2023,
                   step=1,
                   dots=True,
                   value=2016,
                   marks={str(tm):str(tm) for tm in range(2011, 2023)},
                   className='dcc_compon'),
     
    ], style={"margin-bottom": "3vw", 'margin-left':'1%', "border":"2px purple solid", 'background-color':'lightblue'}), 
    
    
    html.Div([
        
        
        html.Div([
             #dropdown country
            html.Div([
                html.H4('Select the country:', className='fix_label',style={'color':'black'}),
                dcc.Dropdown(id='country-selection',
                             multi=False,
                             clearable=True,
                             disabled=False,
                             style={'display':True, 'width':'330px', 'padding':'5px', 'color':'black', 'margin-bottom':'0.5vw'},
                             value='Select all',
                             placeholder='Select  country',
                             options=[{'label': i, 'value': i} for i in country],
                             className='dcc_compon'),
            ], style={'display': 'inline-block', 'vertical-align': 'top', 'margin-left': '0.5vw', 'margin-top': '3vw'}),
                
            html.Br(),
            
            
            
            
            html.Div(id='country-output',
                    style={'margin-left':'0.5vw'}),
            
            html.Br(),
            
            
           
            #dropdown settore
            html.Div([
                html.H4('Which is the sector of interest?', className= 'fix_label', style={'color':'black'}),
                dcc.Dropdown(id='settore-selection',
                             multi=False,
                             clearable=True,
                             disabled=False,
                             style={'display':True, 'width':'330px', 'padding':'5px', 'color':'black', 'margin-bottom':'0.5vw'},
                             placeholder='Select sector',
                             value='All sectors',
                             options=[{'label': z, 'value': z} for z in settore], className='dcc_compon'),
                ], style={'display': 'inline-block', 'vertical-align': 'top', 'margin-left': '0.5vw', 'margin-top': '3vw'}),
                
            html.Br(),
            
            
            
            html.Div(id='settore-output',
                    style={'margin-left':'0.5vw'}),
            
            html.Br(),
            
       
            
        ], style={'background-color':'#FFF0F5','width': '30%', 'display':'inline-block', 'float':'left',"margin-bottom": "10px", 'margin-left':'1%', "border":"2px purple solid"}),
        
        
        
        
        html.Div([
            
            
            
            
            dcc.Graph(id='pie',
                      config={'displayModeBar':'hover'},
                      style={'width':'90%','display':'inline-block','float':'left','margin-left':'0.5%', 'margin-bottom':'1%'}),
            
            
            
            
        ], style={'width': '68%', 'display':'inline-block','float':'right',"margin-bottom": "10px", 'margin-left':'1%', "border":"2px purple solid"}),
        
            
            
        
    ])
    
], id="mainContainer", style={"display":"flex", "flex-direction":"column"})

    @app.callback(Output('pie', 'figure'),
              
              [Input('year-slider', 'value'),

               Input('country-selection', 'value'),

               Input('settore-selection', 'value')])



    def update_graph(year_slider, country_selection, settore_selection):
    
        
    
        m3=df.groupby(['time','geo', 'NACE', 'POSITION'])['sex'].count().reset_index(name='count')
    
        
    
        if country_selection != 'Select all':
    
            m3 = m3[m3['geo']==country_selection]
    
    
    
        m3 = m3[m3['time'] == year_slider]
    
    
        if settore_selection is not None and settore_selection in m3['NACE'].unique():
    
            m3 = m3[m3['NACE']==settore_selection]
    
            
    
        
        fig = make_subplots(rows=1, cols=2, specs=[[{'type':'pie'}, {'type':'pie'}]])
        
        
        fig.add_trace(go.Pie( values=['count'],labels=m3['POSITION'],
                             domain=dict(x=[0, 0.5]), name='Men'),
                  1, 1)
       
        fig.add_trace(go.Pie( values=['count'],labels=m3['POSITION'],
                             
                             domain=dict(x=[0.5, 1.0]), name='Women'),
                  1, 2)
            
        
        # Use `hole` to create a donut-like pie chart
        
        fig.update_traces(hole=.4, hoverinfo="label+percent+name")
        
        fig.update_layout(
            title_text="How the positions are distributed in men and women?",
            # Add annotations in the center of the donut pies.
            annotations=[dict(text='Men', x=0.18, y=0.5, font_size=20, showarrow=False),
                         dict(text='Women', x=0.82, y=0.5, font_size=20, showarrow=False)])    
            
        return fig
    

The dash web does not give me any error, the title appears, also the annotations. But there is no graph.

Part of my .csv file is like this:

,time,_geo,geo,value,UNIT,_UNIT,EGROUP,_EGROUP,POSITION,_POSITION,sex,_sex,NACE,_NACE

1,2015,AT,Austria,2.0,Number of persons (headcount),NR,Largest listed companies,COMP,Employee representatives,EMP_REP,Women,W,"C, E & F (Mining & quarrying; electricity, gas and water; construction)",CEF

2,2015,AT,Austria,8.0,Number of persons (headcount),NR,Largest listed companies,COMP,Employee representatives,EMP_REP,Men,M,"C, E & F (Mining & quarrying; electricity, gas and water; construction)",CEF

3,2015,AT,Austria,0.0,Number of persons (headcount),NR,Largest listed companies,COMP,Executives,EXEC,Women,W,"C, E & F (Mining & quarrying; electricity, gas and water; construction)",CEF

4,2015,AT,Austria,2.0,Number of persons (headcount),NR,Largest listed companies,COMP,CEO (Chief Executive Officer),CEO,Men,M,"C, E & F (Mining & quarrying; electricity, gas and water; construction)",CEF

I have looked online but there are only examples where you single drop the values instead of the column. So presumably the problem may be there

Upvotes: 1

Views: 89

Answers (1)

Derek O
Derek O

Reputation: 19610

There's a few problems in your callback function. Since you want headcount, you should filter only rows where the field _UNIT = NR because these represent absolute numbers of men and women in these positions, then groupby gender and position and then sum the values column.

Upvotes: 1

Related Questions