我正在尝试用Python构建一个仪表板,我想在第一行放置几个下拉菜单。 假设我想创建三个图表(一个直方图、一个条形图、一个饼图),这些图表将从不同图表上方的下拉列表列表中获取。 我是否必须表现得像回调中唯一的一个图表,或者我应该以某种方式连接所有图表?
对于直方图,这是第一个,每当我更改下拉列表值时,我也会在图表中得到更改,但知道我是否尝试重做饼图的回调(饼图输入了一些下拉列表作为直方图,但也有其他下拉列表) )馅饼没有出现。
到目前为止我所做的代码是
app=dash.Dash(__name__, meta_tags=[{"name":"viewport","content":"width=device-width"}],
external_stylesheets=[dbc.themes.MINTY])
management=pd.read_csv('MenWomen.csv')
#fill NAs with zeros
management=management.fillna(0)
#Create the list to show in dropdown element from a specific dataset column
country = management['geo'].unique()
country = country.tolist()
country.insert(0, 'Select all')
sector = management['NACE'].unique()
position = management['POSITION'].unique()
app.layout=html.Div([
html.Div([
html.Div([
html.Div([
html.H3(' title ',
style = {"margin-bottom": "10px", 'textAlign':'center', 'color': '#40E0D0', 'margin-left':'1%'}),
html.H5('subtitle?',
style = {"margin-top":"10px", 'float':'left', 'textAlign':'center'}),
]),
], className="six column", id="title")
], id="header", className="row flex-display", style={"margin-bottom":"25px"}),
html.Div([
html.Div([
html.Div([
html.P('Select the year:', className='fix_label', style={'color':'#2F4F4F', 'margin-left':'1%'}),
dcc.Slider(id='year-slider',
included=False,
updatemode='drag',
tooltip={'always_visible':True},
min=2011,
max=2023,
step=1,
value=2023,
marks={str(tm):str(tm) for tm in range(2011, 2023)},
className='dcc_compon'),
], className="create_container three columns"),
html.Div([
html.Div([
html.P('Select the country:', className='fix_label',style={'color':'black'}),
dcc.Dropdown(id='country-selection',
multi=False,
clearable=True,
disabled=False,
style={'display':True, 'width':'150px', 'padding':'3px', 'color':'black'},
value='Select all',
placeholder='Select country',
options=[{'label': i, 'value': i} for i in country],
className='dcc_compon'),
], style={"border":"2px black solid",'display': 'inline-block', 'vertical-align': 'top', 'margin-left': '5vw', 'margin-top': '3vw'}),
html.Div([
html.P('Choose the sector?', className= 'fix_label', style={'color':'black'}),
dcc.Dropdown(id='sector-selection',
multi=False,
clearable=True,
disabled=False,
style={'display':True, 'width':'430px', 'padding':'3px', 'color':'black'},
placeholder='Select sector',
value='All sectors',
options=[{'label': z, 'value': z} for z in settore], className='dcc_compon'),
], style={"border":"2px black solid",'display': 'inline-block', 'vertical-align': 'top', 'margin-left': '5vw', 'margin-top': '3vw'}),
html.Div([
html.P('Select the posiion?', className='fix_label', style={'color':'black'}),
dcc.Dropdown(id='position-selection',
multi=False,
clearable=True,
disabled=False,
style={'display':True, 'width':'300px', 'padding':'3px', 'color':'black'},
placeholder='Select the position',
value='CEO (Chief Executive Officer)',
options=[{'label': k, 'value': k} for k in position],
className = 'dcc_compon'),
], style={"border":"2px black solid",'display': 'inline-block', 'vertical-align': 'top', 'margin-left': '5vw', 'margin-top': '3vw'}),
]),
]),
], className="row flex-display", style={"border":"2px #3CB371 solid", "background":"#F0FFF0"}),
html.Br(),
#second row
html.Div([
html.Div([
html.Div([
dcc.Graph(id='histogram',
config={'displayModeBar':'hover'},
style={'width':'100%','display':'inline-block','float':'left'}),
dcc.Graph(id='piechart',
#position based on sector, year, country
config={'displayModeBar':'hover'},
style={'width':'49%','display':'inline-block','float':'left'}),
], className="one-half column", style={"border":"2px black solid","margin-top":"10px", 'width':'49%', 'display':'inline-block', 'float':'left', 'textAlign':'center'}),
])
], className="row flex-display"),
], id="mainContainer", style={"display":"flex", "flex-direction":"column"})
#create histogram
@app.callback(
Output("histogram", "figure"),
[Input("country-selection", "value"),
Input("sector-selection","value"),
Input("position-selection","value")]
)
def graph_update(country_selection, sector_selection, position_selection):
m1=management
if country_selection != 'Select all':
m1 = m1[m1['geo']==country_selection]
m1 = m1[m1['NACE']==sector_selection]
if position_selection is not None and position_selection in m1['POSITION'].unique():
m1 = m1[m1['POSITION']==position_selection]
fig=px.histogram(m1, x='time', y='value', color='sex', barmode='group')
return fig
#Callback definition for the dynamic update of dropdown list
@app.callback(
Output('position-selection', 'options'),
[Input('sector-selection', 'value'),
Input('country-selection', 'value')]
)
def update_position_selection(sector_selection, country_selection):
if country_selection != 'Select all':
list_values = management[(management['geo']==country_selection) & (management['NACE'] == sector_selection)]['POSITION'].unique()
else:
list_values = management[management['NACE'] == sector_selection]['POSITION'].unique()
return [{'label': p, 'value': p} for p in list_values]
#now is the part that I can't seem to make it work,
#I want to obtain two pies one for men and one for women
#create piechart
@app.callback(
Output("piechart", "figure"),
[Input("country-selection", "value"),
Input("sector-selection", "value"),
Input("year-slider","value")]
)
def update_piechart( country_selection, sector_selection, year_slider):
m2=management.groupby(['geo', 'NACE', 'year'])['gendre'].sum().reset_index()
if country_selection != 'Select all':
management2 = management2[management2['geo']==country_selection]
management2 = management2[management2['NACE']==sector_selection]
if year_slider is not None and year_slider in management2['year'].unique():
management2 = management2[management2['year']==year_slider]
fig=go.Pie(management2, labels=['POSITION'],
values = 'POSITION',
marker = dict(colors = 'gendre'),
hoverinfo = 'label+value+percent',
textinfo = 'label+value',
textfont = dict(size = 13),
hole=.7,
),
return fig
if __name__ == '__main__':
app.run_server(debug=True, use_reloader=False)
管理档案是这样的,所以基本上每个国家都一一列出,每年都写了每个性别、在某个部门、扮演某个角色的人数
,year,_geo,geo,value,UNIT,_UNIT,EGROUP,_EGROUP,POSITION,_POSITION,gendre,_gendre,NACE,_NACE
0,2012,AT,Austria,0.0,Number of persons (headcount),NR,Largest listed companies,COMP,CEO (Chief Executive Officer),CEO,Women,W,"C, E & F (Mining & quarrying; electricity, gas and water; construction)",CEF
1,2013,AT,Austria,0.0,Number of persons (headcount),NR,Largest listed companies,COMP,CEO (Chief Executive Officer),CEO,Women,W,"C, E & F (Mining & quarrying; electricity, gas and water; construction)",CEF
2,2014,AT,Austria,0.0,Number of persons (headcount),NR,Largest listed companies,COMP,CEO (Chief Executive Officer),CEO,Women,W,"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,CEO (Chief Executive Officer),CEO,Women,W,"C, E & F (Mining & quarrying; electricity, gas and water; construction)",CEF
4,2016,AT,Austria,0.0,Number of persons (headcount),NR,Largest listed companies,COMP,CEO (Chief Executive Officer),CEO,Women,W,"C, E & F (Mining & quarrying; electricity, gas and water; construction)",CEF
5,2017,AT,Austria,0.0,Number of persons (headcount),NR,Largest listed companies,COMP,CEO (Chief Executive Officer),CEO,Women,W,"C, E & F (Mining & quarrying; electricity, gas and water; construction)",CEF
6,2018,AT,Austria,0.0,Number of persons (headcount),NR,Largest listed companies,COMP,CEO (Chief Executive Officer),CEO,Women,W,"C, E & F (Mining & quarrying; electricity, gas and water; construction)",CEF
7,2019,AT,Austria,0.0,Number of persons (headcount),NR,Largest listed companies,COMP,CEO (Chief Executive Officer),CEO,Women,W,"C, E & F (Mining & quarrying; electricity, gas and water; construction)",CEF
8,2020,AT,Austria,0.0,Number of persons (headcount),NR,Largest listed companies,COMP,CEO (Chief Executive Officer),CEO,Women,W,"C, E & F (Mining & quarrying; electricity, gas and water; construction)",CEF
9,2021,AT,Austria,0.0,Number of persons (headcount),NR,Largest listed companies,COMP,CEO (Chief Executive Officer),CEO,Women,W,"C, E & F (Mining & quarrying; electricity, gas and water; construction)",CEF
您的
update_piechart
函数有两个问题:
fig = go.Figure(data=go.Pie(...))
.count
而不是 .sum
您可能需要对我的代码进行进一步更改才能获得您想要的结果,但饼图现在呈现:
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
import dash
from dash import html, dcc, Input, Output
import dash_bootstrap_components as dbc
app=dash.Dash(__name__, meta_tags=[{"name":"viewport","content":"width=device-width"}],
external_stylesheets=[dbc.themes.MINTY])
management=pd.read_csv('MenWomen.csv')
#fill NAs with zeros
management=management.fillna(0)
#Create the list to show in dropdown element from a specific dataset column
country = management['geo'].unique()
country = country.tolist()
country.insert(0, 'Select all')
sector = management['NACE'].unique()
position = management['POSITION'].unique()
app.layout=html.Div([
html.Div([
html.Div([
html.Div([
html.H3(' title ',
style = {"margin-bottom": "10px", 'textAlign':'center', 'color': '#40E0D0', 'margin-left':'1%'}),
html.H5('subtitle?',
style = {"margin-top":"10px", 'float':'left', 'textAlign':'center'}),
]),
], className="six column", id="title")
], id="header", className="row flex-display", style={"margin-bottom":"25px"}),
html.Div([
html.Div([
html.Div([
html.P('Select the year:', className='fix_label', style={'color':'#2F4F4F', 'margin-left':'1%'}),
dcc.Slider(id='year-slider',
included=False,
updatemode='drag',
tooltip={'always_visible':True},
min=2011,
max=2023,
step=1,
value=2023,
marks={str(tm):str(tm) for tm in range(2011, 2023)},
className='dcc_compon'),
], className="create_container three columns"),
html.Div([
html.Div([
html.P('Select the country:', className='fix_label',style={'color':'black'}),
dcc.Dropdown(id='country-selection',
multi=False,
clearable=True,
disabled=False,
style={'display':True, 'width':'150px', 'padding':'3px', 'color':'black'},
value='Select all',
placeholder='Select country',
options=[{'label': i, 'value': i} for i in country],
className='dcc_compon'),
], style={"border":"2px black solid",'display': 'inline-block', 'vertical-align': 'top', 'margin-left': '5vw', 'margin-top': '3vw'}),
html.Div([
html.P('Choose the sector?', className= 'fix_label', style={'color':'black'}),
dcc.Dropdown(id='sector-selection',
multi=False,
clearable=True,
disabled=False,
style={'display':True, 'width':'430px', 'padding':'3px', 'color':'black'},
placeholder='Select sector',
value='All sectors',
options=[{'label': z, 'value': z} for z in sector], className='dcc_compon'),
], style={"border":"2px black solid",'display': 'inline-block', 'vertical-align': 'top', 'margin-left': '5vw', 'margin-top': '3vw'}),
html.Div([
html.P('Select the posiion?', className='fix_label', style={'color':'black'}),
dcc.Dropdown(id='position-selection',
multi=False,
clearable=True,
disabled=False,
style={'display':True, 'width':'300px', 'padding':'3px', 'color':'black'},
placeholder='Select the position',
value='CEO (Chief Executive Officer)',
options=[{'label': k, 'value': k} for k in position],
className = 'dcc_compon'),
], style={"border":"2px black solid",'display': 'inline-block', 'vertical-align': 'top', 'margin-left': '5vw', 'margin-top': '3vw'}),
]),
]),
], className="row flex-display", style={"border":"2px #3CB371 solid", "background":"#F0FFF0"}),
html.Br(),
#second row
html.Div([
html.Div([
html.Div([
dcc.Graph(id='histogram',
config={'displayModeBar':'hover'},
style={'width':'100%','display':'inline-block','float':'left'}),
dcc.Graph(id='piechart',
#position based on sector, year, country
config={'displayModeBar':'hover'},
style={'width':'49%','display':'inline-block','float':'left'}),
], className="one-half column", style={"border":"2px black solid","margin-top":"10px", 'width':'49%', 'display':'inline-block', 'float':'left', 'textAlign':'center'}),
])
], className="row flex-display"),
], id="mainContainer", style={"display":"flex", "flex-direction":"column"})
#create histogram
@app.callback(
Output("histogram", "figure"),
[Input("country-selection", "value"),
Input("sector-selection","value"),
Input("position-selection","value")]
)
def graph_update(country_selection, sector_selection, position_selection):
m1=management
if country_selection != 'Select all':
m1 = m1[m1['geo']==country_selection]
m1 = m1[m1['NACE']==sector_selection]
if position_selection is not None and position_selection in m1['POSITION'].unique():
m1 = m1[m1['POSITION']==position_selection]
fig=px.histogram(m1, x='year', y='value', color='gendre', barmode='group')
return fig
#Callback definition for the dynamic update of dropdown list
@app.callback(
Output('position-selection', 'options'),
[Input('sector-selection', 'value'),
Input('country-selection', 'value')]
)
def update_position_selection(sector_selection, country_selection):
if country_selection != 'Select all':
list_values = management[(management['geo']==country_selection) & (management['NACE'] == sector_selection)]['POSITION'].unique()
else:
list_values = management[management['NACE'] == sector_selection]['POSITION'].unique()
return [{'label': p, 'value': p} for p in list_values]
#now is the part that I can't seem to make it work,
#I want to obtain two pies one for men and one for women
#create piechart
@app.callback(
Output("piechart", "figure"),
[Input("country-selection", "value"),
Input("sector-selection", "value"),
Input("year-slider","value")]
)
def update_piechart( country_selection, sector_selection, year_slider):
management2=management.groupby(['geo', 'NACE', 'year', 'POSITION'])['gendre'].count().reset_index(name='count')
if country_selection != 'Select all':
management2 = management2[management2['geo']==country_selection]
management2 = management2[management2['NACE']==sector_selection]
if year_slider is not None and year_slider in management2['year'].unique():
management2 = management2[management2['year']==year_slider]
fig=go.Figure(data=[go.Pie(labels=management2['POSITION'],
values = management2['count'],
# marker = dict(colors = 'gendre'),
hoverinfo = 'label+value+percent',
textinfo = 'label+value',
textfont = dict(size = 13),
hole=.7,
)]
)
return fig
if __name__ == '__main__':
app.run_server(debug=True, use_reloader=False)