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

Dash应用选择下拉选项后无输出容器显示(无报错)求助

Dash应用下拉选择后无输出的问题修复

核心问题及修复点:

  • 回调参数顺序错位:第二个回调的输入顺序是select-year在前、dropdown-statistics在后,但函数参数顺序相反,导致参数值匹配错误。调整函数参数顺序为input_year, dropdown_options即可。
  • groupby后未执行reset_index:多处reset_index未加括号,导致返回方法对象而非DataFrame,修正为reset_index()。
  • 图表参数错误:
    • 饼图错误使用不存在的pop列,替换为实际的Advertising_Expenditure列;
    • 直方图语法错误,修正参数传递方式,同时修正数据过滤条件的语法错误,注意原数据中失业率列名为Unemployment_Rate(大写开头);
    • 月度销量图的dcc.Graph写法错误,需用figure=px.line()包裹绘图逻辑。
  • 未处理年份为空的情况:选择Yearly Statistics但未选年份时,input_year为None,添加判断避免报错。

修复后的完整代码:

import dash
from dash import dcc
from dash import html
from dash.dependencies import Input, Output
import pandas as pd
import plotly.express as px

# Load the data using pandas
data = pd.read_csv('https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-DV0101EN-SkillsNetwork/Data%20Files/historical_automobile_sales.csv')

# Initialize the Dash app
app = dash.Dash(__name__)

# Set the title of the dashboard
app.title = "Automobile Statistics Dashboard"

# List of years 
year_list = [i for i in range(1980, 2024, 1)]

# Create the layout of the app
app.layout = html.Div([
    html.H1("Automobile Sales Statistics Dashboard", style={'textAlign': 'center', 'color': '#503D36', 'font-size': 24}),
    html.Div([
        html.Label("Select Statistics:"),
        dcc.Dropdown(
            id='dropdown-statistics',
            options=[
                {'label': 'Yearly Statistics', 'value': 'Yearly Statistics'},
                {'label':'Recession Period Statistics', 'value': 'Recession Period Statistics'}
            ],
            placeholder='Select a report type',
            style={'width': '80%', 'padding':'3px', 'font-size':'20px', 'text-align-last':'center'}
        )
    ]),
    html.Div(dcc.Dropdown(
            id='select-year',
            options=[{'label': i, 'value': i} for i in year_list],
            placeholder='Select a year',
            style={'width': '80%', 'padding':'3px', 'font-size':'20px', 'text-align-last':'center'}
        )),
    html.Div([
        html.Div(id='output_container', className='chart-grid', style={'display':'flex', 'flex-wrap': 'wrap'}),
    ])
])

# Callback to toggle year dropdown disable state
@app.callback(
    Output(component_id='select-year', component_property='disabled'),
    Input(component_id='dropdown-statistics', component_property='value'))
def update_input_container(selected_stat):
    return selected_stat != 'Yearly Statistics'

# Callback for plotting
@app.callback(
    Output(component_id='output_container', component_property='children'),
    [Input(component_id='select-year', component_property='value'), 
     Input(component_id='dropdown-statistics', component_property='value')])
def update_output_container(input_year, dropdown_options):
    if dropdown_options == 'Recession Period Statistics':
        recession_data = data[data['Recession'] == 1]
        
        # Plot 1: Average Automobile Sales over Recession Period
        yearly_rec = recession_data.groupby('Year')['Automobile_Sales'].mean().reset_index()
        R_chart1 = dcc.Graph(
            figure=px.line(yearly_rec, 
                          x='Year', y='Automobile_Sales',
                          title="Average Automobile Sales Fluctuation over Recession Period"))

        # Plot 2: Average Sales by Vehicle Type
        average_sales = recession_data.groupby(['Vehicle_Type'])['Automobile_Sales'].mean().reset_index()                           
        R_chart2 = dcc.Graph(figure=px.bar(average_sales, x='Vehicle_Type', y='Automobile_Sales', 
                                           title='Average Number of Vehicles Sold by Vehicle Type'))
        
        # Plot 3: Total Expenditure Share by Vehicle Type
        exp_rec = recession_data.groupby(['Vehicle_Type'])['Advertising_Expenditure'].sum().reset_index()
        R_chart3 = dcc.Graph(figure=px.pie(exp_rec, values='Advertising_Expenditure', names='Vehicle_Type', 
                                           title='Total Expenditure Share by Vehicle Type during Recessions'))

        # Plot 4: Unemployment Rate Effect on Vehicle Sales
        R_chart4 = dcc.Graph(figure=px.histogram(recession_data, x='Unemployment_Rate', hue='Vehicle_Type',
                                                title='Effect of Unemployment Rate on Vehicle Type and Sales'))

        return [
            html.Div(className='chart-grid', children=[R_chart1, R_chart2], style={'display': 'flex', 'width': '100%', 'gap': '20px'}),
            html.Div(className='chart-grid', children=[R_chart3, R_chart4], style={'display': 'flex', 'width': '100%', 'gap': '20px', 'margin-top': '20px'})
        ]
    elif dropdown_options == 'Yearly Statistics' and input_year is not None:
        yearly_data = data[data['Year'] == input_year]
        
        # Plot 1: Overall Yearly Sales Trend
        yas = data.groupby('Year')['Automobile_Sales'].mean().reset_index()
        Y_chart1 = dcc.Graph(figure=px.line(yas, 
                                           x='Year', y='Automobile_Sales',
                                           title="Average Automobile Sales Fluctuation over Time"))
            
        # Plot 2: Monthly Sales for Selected Year
        monthly_sales = yearly_data.groupby('Month')['Automobile_Sales'].sum().reset_index()
        Y_chart2 = dcc.Graph(figure=px.line(monthly_sales, x='Month', y='Automobile_Sales',
                                           title=f'Total Monthly Automobile Sales in {input_year}'))

        # Plot 3: Average Sales by Vehicle Type in Selected Year
        avr_vdata = yearly_data.groupby(['Vehicle_Type'])['Automobile_Sales'].mean().reset_index()
        Y_chart3 = dcc.Graph(figure=px.bar(avr_vdata, x='Vehicle_Type', y='Automobile_Sales', hue='Vehicle_Type',
                                          title=f'Average Vehicles Sold by Vehicle Type in {input_year}'))

        # Plot 4: Total Advertising Expenditure Share
        exp_data = yearly_data.groupby(['Vehicle_Type'])['Advertising_Expenditure'].sum().reset_index()
        Y_chart4 = dcc.Graph(figure=px.pie(exp_data, values='Advertising_Expenditure', names='Vehicle_Type',
                                          title='Total Expenditure Share by Vehicle Type'))

        return [
            html.Div(className='chart-grid', children=[Y_chart1, Y_chart2], style={'display': 'flex', 'width': '100%', 'gap': '20px'}),
            html.Div(className='chart-grid', children=[Y_chart3, Y_chart4], style={'display': 'flex', 'width': '100%', 'gap': '20px', 'margin-top': '20px'})
        ]
    else:
        return html.Div("Please select a valid report type and year (if applicable)", style={'padding': '20px'})

# Run the Dash app
if __name__ == '__main__':
    app.run_server(debug=True)

内容的提问来源于stack exchange,提问作者Olufade Toheeb

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 17:17:02