我正在学习python /破折号,并尝试制作可通过列值“ Manager”过滤的堆叠条形图-初始化时我能够生成默认的堆叠条形图(针对value = "All Managers"
),但是在选择给定的管理器后(通过单击下拉菜单上的x),尝试恢复为默认值时出现关键错误。
选择那些没有所有“堆栈”数据的管理器时,也会遇到关键错误。
例如,对于Manager#5,如果Manager#5的“活动类型”列中没有“个人培训”数据点,则会收到“个人培训”的关键错误。
另一方面,对于经理2,堆积的条形图显示该经理的数据没有错误,但是当我单击x清除下拉列表时,该值不会恢复为初始值。
关于重置下拉列表时出现的关键错误,我可以通过以下方法解决:将mgr_options转换为列表,将初始值“ All Managers”插入列表,然后将“ clearable”设置为False。
关于为每种“活动类型”类型选择没有列值的管理器时遇到的主要错误,我尝试用if语句包装Go.Bar定义,但是没有运气。有什么建议吗?
下面是我的代码
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
import pandas as pd
from dash.dependencies import Input, Output
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
movement_activity_file = 'PATH_TO_FILE'
df = pd.read_excel(movement_activity_file,
sheet_name="Activity Report")
df = df.loc[:,['Activity Type','Group','Manager']]
mgr_options = df["Manager"].unique()
app.layout = html.Div(children=[
html.H1(children='Sample Text'),
html.Div(children='''Sample Text'''),
html.Div(
[
dcc.Dropdown(
id="Manager",
options=[{
'label': i,
'value': i
} for i in mgr_options],
value = 'All Managers'),
],
style={'width': '25%',
'display': 'inline-block'}),
dcc.Graph(id='activity-graph'),
])
@app.callback(
dash.dependencies.Output('activity-graph', 'figure'),
[dash.dependencies.Input('Manager, 'value')])
def update_graph(Manager):
if Manager == "All Managers":
df_plot = df.copy()
else:
df_plot = df[df['Manager'] == Manager]
sum_typs = pd.pivot_table(df_plot,
index=['Group'],
columns = ['Activity Type'],
aggfunc=len,
fill_value=0)
grp_trn = go.Bar(x=sum_typs.index, y=sum_typs['Manager']['Group Training'], name='Group Training')
phn_cll = go.Bar(x=sum_typs.index, y=sum_typs['Manager']['Phone Call'], name='Phone Call')
gym_ent = go.Bar(x=sum_typs.index, y=sum_typs['Manager']['Entry to Gym'], name='Entry to Gym')
prs_ntr = go.Bar(x=sum_typs.index, y=sum_typs['Manager']['Personal Nutrition'], name='Personal Nutrition')
grp_emp = go.Bar(x=sum_typs.index, y=sum_typs['Manager']['Group Empowerment'], name='Group Empowerment')
prs_trn = go.Bar(x=sum_typs.index, y=sum_typs['Manager']['Personal Training'], name='Personal Training')
grp_ntr = go.Bar(x=sum_typs.index, y=sum_typs['Manager']['Group Nutrition'], name='Group Nutrition')
return{
'data': [grp_trn, phn_cll, gym_ent ,prs_ntr, grp_emp, prs_trn, grp_ntr],
'layout':
go.Layout(
title='Activities by {}'.format(Manager),
barmode='stack')
}
if __name__ == '__main__':
app.run_server(debug=True)