You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Dash Plotly双输入绑定输出、柱状图X轴排序及筛选代码问题咨询

原代码核心错误点

  • 回调筛选逻辑错误:判断条件错误写为country == 'value',实际应该判断是否为全局选项All,且没有处理单维度选All的场景
  • 代码缩进错误:图表生成代码未放在回调函数的作用域内,导致参数变更无法触发生成新图
  • 柱状图维度不匹配:x轴取Week字段、y轴直接取Source的value_counts,二者维度长度不一致,无法正确对应
  • X轴排序逻辑缺失:未对Week字段做有序分类处理,导致X轴展示顺序混乱

修复后完整代码

import dash
from dash import dcc, html, Input, Output
import plotly.graph_objects as go
import pandas as pd

# 替换为你自己的数据源加载逻辑
# df = pd.read_csv('你的数据文件路径.csv')

app = dash.Dash(__name__)

app.layout = html.Div([
    html.Div([
        html.Div([
            html.H3('Select a Country'),
            dcc.Dropdown(id = 'drop',
                        options =[{'label': i, 'value': i} for i in df["Country"].unique()] + [{'label': 'Select all', 'value': 'All'}], 
                        value='All')
        ],style={'width': '35%','display':'inline-block'}),

        html.Div([
            html.H3('Select a Reason'),
            dcc.Dropdown(id = 'drop1',
                        options =[{'label': i, 'value': i} for i in df["Source"].unique()] + [{'label': 'Select all', 'value': 'All'}], 
                        value='All')
        ],style={'width': '35%','display':'inline-block'}),
    ], className="row"),
    html.Div(dcc.Graph(id = "graph"))
],style={'width': '100%', 'display': 'inline-block'})

@app.callback(Output('graph','figure'),
          [Input('drop', 'value'),Input('drop1', 'value')])
def update_graph(country,reason):
    # 多条件筛选逻辑
    filter_mask = pd.Series([True]*len(df))
    if country != 'All':
        filter_mask &= (df['Country'] == country)
    if reason != 'All':
        filter_mask &= (df['Source'] == reason)
    dff = df[filter_mask].copy()
    
    # 处理周维度排序,若你的Week为纯数字格式可自行调整提取逻辑
    dff['week_num'] = dff['Week'].str.extract('(\d+)').astype(int)
    week_order = dff.sort_values('week_num')['Week'].unique()
    dff['Week'] = pd.Categorical(dff['Week'], categories=week_order, ordered=True)
    
    # 按周聚合订单数量
    week_stat = dff.groupby('Week', observed=True)['Source'].count().reset_index(name='order_count')
    
    # 生成柱状图
    fig = go.Figure([go.Bar(x=week_stat["Week"], y=week_stat["order_count"])]) 
    fig.update_layout(barmode='relative', title_text='Number of Orders')
    return fig

if __name__ == '__main__':
    app.run_server(debug=True)

内容的提问来源于stack exchange,提问作者Ahmed Galal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 23:57:02