DASH回调更新graph.figure报错:邮编选择后直方图异常
问题修复:Dash下拉菜单选择邮编触发直方图报错
错误原因与修复点
- 数据类型错误:
dropdown_changed函数的else分支中,datalist2 = datalist[datalist['Postcode'].isin(postcodes)],末尾多了一个逗号,导致datalist2变成包含DataFrame的元组,而非直接的DataFrame,传给px.histogram时会因类型不匹配报错,需删除该逗号。 - 颜色逻辑覆盖:原代码中统一执行
fig.update_traces(marker=dict(color="#002664")),会覆盖color='Postcode'的颜色区分效果,导致选中邮编后无法看到不同邮编的颜色差异,需仅在默认无选中状态时保留该设置。 - 冗余代码优化:原代码中
pd.Series(datalist['Postcode'].unique()).sort_values(ascending=True)未赋值给变量,属于无效代码,可简化为sorted(datalist['Postcode'].unique())生成排序后的邮编列表。
修正后完整代码
import pandas as pd import plotly.express as px from dash import Dash, html, dcc, Input, Output app = Dash(__name__) app.title = "EGMs in NSW" # 加载数据 datalist = pd.read_excel('premises-list-Aug-2022.xlsx', skiprows=[0,1,2]) datalist['Licence type'] = datalist['Licence type'].str.split(" - ").str.get(1) datalist['Licence type'] = datalist['Licence type'].str.title() # 生成去重并排序的邮编列表 postcode = sorted(datalist['Postcode'].unique()) def make_histogram_plot(): fig = px.histogram( data_frame=datalist, x='Licence type', y='EGMs', color='Postcode', title='EGMs by Licence Type in NSW', histfunc='avg' ) # 默认状态下统一颜色 fig.update_traces(marker=dict(color="#002664")) fig.update_layout( plot_bgcolor='#EAEDF4', xaxis_title=None, yaxis_title='Average EGMs' ) return fig app.layout = html.Div(children=[ html.Div([ dcc.Dropdown(postcode, value=[], placeholder="Select postcodes", multi=True, id='postcodes') ]), dcc.Graph(id='graph', figure=make_histogram_plot()) ]) @app.callback( Output('graph', 'figure'), Input('postcodes', 'value') ) def dropdown_changed(postcodes): if postcodes == []: fig = make_histogram_plot() else: datalist2 = datalist[datalist['Postcode'].isin(postcodes)] fig = px.histogram( data_frame=datalist2, x='Licence type', y='EGMs', color='Postcode', title='EGMs by Licence Type in NSW', histfunc='avg' ) fig.update_layout( plot_bgcolor='#EAEDF4', xaxis_title=None, yaxis_title='Average EGMs' ) return fig if __name__ == '__main__': app.run_server(debug=True)
内容的提问来源于stack exchange,提问作者ZJJ
相关产品推荐
相关产品推荐

