如何让Dash应用图表随下拉选项更新?啤酒销售数据过滤问题
问题原因及修复方案
你的下拉菜单失效是因为回调函数完全没用到选中的分类值过滤数据,反而错误地把分类名称当成了颜色刻度参数,这两个问题导致图表不会随下拉选项更新。
具体问题点
- 回调中创建
new_df时,直接对整个原始数据集分组,没有根据选中的Major Category筛选数据。 color_continuous_scale参数接收的是颜色刻度(如'Viridis'),但你传入了下拉选中的分类名称(如'ALCOHOL'),这属于参数误用。
修复后的完整代码
# Import required libraries import pandas as pd import dash import dash_html_components as html import dash_core_components as dcc from dash.dependencies import Input, Output from jupyter_dash import JupyterDash import plotly.express as px file_loc = "https://raw.githubusercontent.com/Barbj379/Two_Ton/main/Item%20Sales%20Report.csv" df = pd.read_csv(file_loc) # Create a dash application app = JupyterDash(__name__) app.layout= html.Div(children=[ # New Div for all elements in the new 'row' of the page html.Div([ html.H1(children='Two Ton Dash'), html.Div(children=''' Sales report of last fiscal quarter. '''), html.Div([ dcc.Graph(id='graph0'), html.Label(["Category", dcc.Dropdown( id='category-dropdown', clearable=False, value='ALCOHOL', options=[ {'label': c, 'value': c} for c in df['Major Category'].unique() ]) ]), ]), ]) ]) # Callback function that automatically updates the graph based on chosen category @app.callback( Output('graph0', 'figure'), [Input("category-dropdown", "value")] ) def update_figure(selected_category): # 根据选中的主类别过滤数据 filtered_df = df[df['Major Category'] == selected_category] # 对过滤后的数据按子类别和商品名分组计算销售额总和 new_df = filtered_df.groupby(['Minor Category', 'Item Name'])['Net Sales'].sum().reset_index() # 生成柱状图,使用离散颜色区分商品名 fig = px.bar( new_df, x="Minor Category", y="Net Sales", color="Item Name", title=f"Items in {selected_category} Category" ) return fig if __name__ == '__main__': app.run_server(debug=True)
关键修改说明
- 添加
filtered_df = df[df['Major Category'] == selected_category]:用选中的主类别过滤原始数据,确保只处理对应分类的商品。 - 移除错误的
color_continuous_scale=Category参数:Item Name是离散分类,Plotly会自动分配离散颜色,不需要连续颜色刻度。 - 优化图表标题:动态显示当前选中的主类别,提升可读性。
内容的提问来源于stack exchange,提问作者Mike Barbiere
相关产品推荐
相关产品推荐

