我正在 Coursera 上参加 IBM 数据科学认证课程,并且正在尝试使用 Google Colab 使用 Plotly 和 Dash 创建仪表板。 该分配包括两个下拉列表(选择报告类型和年份),并且根据用户的选择,它将输出 4 个图表。仅当用户从前一个下拉列表中选择“年度统计报告”时,才应启用第二个下拉列表(用于选择年份),否则仅应禁用它。 - 仅当用户从前一个下拉列表中选择“年度统计报告”时,才应启用第二个下拉列表(用于选择年份),否则仅应禁用它。返回布局并显示图形的回调函数。将需要第一个回调来获取报告类型的输入,并将年份下拉列表设置为启用以获取“年份统计报告”的年份输入,否则此下拉列表将被禁用。在第二个回调中,它应该获取报告类型和年份的值,并为每种类型的报告相应地返回所需的图表。 但是,当我尝试在下拉菜单中选择一个选项时,我看不到任何图表,并且在更新 output-container.children 时收到回调错误。 我将非常感谢任何帮助。 这是我的代码:
import dash
from dash import dcc
from dash import html
from dash.dependencies import Input, Output
import pandas as pd
import plotly.graph_objs as go
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"
dropdown_options = [
{'label': 'Yearly Statistics Report', 'value': 'Yearly Statistics'},
{'label': 'Recession Period Statistics', 'value': 'Recession Period Statistics'}
]
# List of years
year_list = [i for i in range(1980, 2024, 1)]
# Initialize the Dash app
app = dash.Dash(__name__)
# Set the title of the dashboard
#app.title = "Automobile Statistics Dashboard"
dropdown_options = [
{'label': 'Yearly Statistics Report', 'value': 'Yearly Statistics'},
{'label': 'Recession Period Statistics', 'value': 'Recession Period Statistics'}
]
# List of years
year_list = [i for i in range(1980, 2024, 1)]
# Create the layout of the app
app.layout = html.Div(children=[
#TASK 2.1 Add title to the dashboard
html.H1("Automobile Sales Statistics Dashboard", style={'textAlign': 'center', 'color': '#503D36', 'font-size': 24}),
html.Div ([
#TASK 2.2: Add two dropdown menus
html.Label("Select Statistics:"),
dcc.Dropdown (id='dropdown-statistics',
options=[
{'label': 'Yearly Statistics', 'value': 'Yearly Statistics'},
{'label': 'Recession Period Statistics', 'value': 'Recession Period Statistics'}],
value='Select Statistics',
placeholder='Select a report type',
style={'textAlign': 'center', 'width': '80%', 'padding': 3, 'font-size': 20})
]),
html.Div(
dcc.Dropdown(id='select-year',
options=[{'label': i, 'value': i} for i in year_list],
value='Select Year',
style={'textAlign': 'center', 'width': '80%', 'padding': 3, 'font-size': 20}
)),
html.Div([
#TASK 2.3: Add a division for output display
html.Div(id='output-container',
className='chart-grid',
style={'display': 'flex'})])
])
#TASK 2.4: Creating Callbacks
# Define the callback function to update the input container based on the selected statistics
@app.callback(
Output(component_id='select-year', component_property='disabled'),
Input(component_id='dropdown-statistics', component_property='value'))
def update_input_container(selected_statistics):
if selected_statistics =='Yearly Statistics':
return False
else:
return True
#Callback for plotting
# Define the callback function to update the input container based on the selected statistics
@app.callback(
Output(component_id='output-container', component_property='children'),
[Input(component_id='dropdown-statistics',component_property='value'),
Input(component_id='select-year', component_property='value')])
def update_output_container(selected_statistics, input_year):
if selected_statistics == 'Recession Period Statistics':
#TASK 2.5: Create and display graphs for Recession Report Statistics
#Plot 1 Automobile sales fluctuate over Recession Period (year wise)
recession_data = data[data['Recession'] == 1]
yearly_data = data[data['Year'] == input_year]
yearly_rec = recession_data.groupby('Year')['Automobile_Sales'].mean().reset_index()
R_chart1 = dcc.Graph(
figure=px.line(yearly_rec,
x='Year',
y='Sales Volume',
title="Average Automobile Sales fluctuation over Recession Period"))
#Plot 2 Calculate the average number of vehicles sold by vehicle type
average_sales = data.groupby('Vehicle_Type')['Automobile_Sales'].mean().reset_index()
R_chart2 = dcc.Graph(
figure=px.bar(average_sales,
x='Vehicle Type',
y='Sales Volume',
title='Average Number of Vehicles Sold by Vehicle Type'))
# Plot 3 Pie chart for total expenditure share by vehicle type during recession
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 Expendiure Share by Vehicle Type during Recessions"))
# Plot 4 bar chart for the effect of unemployment rate on vehicle type and sales
un_sales = data.groupby(['Vehicle_Type', 'unemployment_rate'])['Automobile_Sales'].mean().reset_index()
R_chart4 = dcc.Graph(
figure=px.bar(un_sales,
x='Unemployment Rate',
y='Sales Volume',
title='The Effect of Unemployment Rate on Vehicle Type and Sales'))
return[html.Div(className='chart-grid', children=[html.Div(children=R_chart1),html.Div(children=R_chart2)], style={'display': 'flex'}),
html.Div(className='chart-grid', children=[html.Div(children=R_chart3),html.Div(children=R_chart4)], style={'display': 'flex'})]
elif (input_year and selected_statistics =='Yearly Statistics'):
yearly_data = data[data['Year'] == input_year]
#plot 1 Yearly Automobile sales using line chart for the whole period.
yas= data.groupby('Year')['Automobile_Sales'].sum().reset_index()
Y_chart1 = dcc.Graph(
figure=px.line(yas,
x='Year',
y='Sales Volume',
title='Yearly Automobile Sales'))
# Plot 2 Total Monthly Automobile sales using line chart.
mas=data.groupby('Month')['Automobile_Sales'].sum().reset_index()
Y_chart2 = dcc.Graph(
figure=px.line(mas,
x='Month',
y='Sales Volume',
title='Total Monthly Automobile Sales'))
# Plot bar chart for average number of vehicles sold during the given year
avr_vdata=yearly_data.groupby('Year')['Automobile_Sales'].mean().reset_index()
Y_chart3 = dcc.Graph(
figure=px.bar(avr_vdata,
x='Year',
y='Sales Volume',
title='Average Vehicles Sold by Vehicle Type in the year {}'.format(input_year)))
# Total Advertisement Expenditure for each vehicle using pie chart
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 Advertisement Expenditure for Each Vehicle Type"))
#TASK 2.6: Returning the graphs for displaying Yearly data
return [html.Div(className='chart-grid', children=[html.Div(children=Y_chart1),html.Div(children=Y_chart2)], style={'display': 'flex'}),
html.Div(className='chart-grid', children=[html.Div(children=Y_chart3),html.Div(children=Y_chart4)], style={'display': 'flex'})]
else:
return None
# Run the Dash app
if __name__ == '__main__':
app.run_server(debug=True)
我检查了所有语法错误,现在看不到任何错误。也许我需要用新的眼光来看待。 我检查了数据:一切正常,加载和格式正确。 我还尝试添加 html.Div 和输出。之后我可以看到空图和一个新错误:回调错误更新..chart1.figure...chart2.figure...chart3.figure...chart4.figure..
html.Div(style={'display': 'flex', 'justify-content': 'center'},
children=[html.Div(dcc.Graph(id='chart1'), style={'border': 'ridge', 'padding': '10px', 'backgroundColor': '#00008B'}),
html.Div(dcc.Graph(id='chart2'), style={'border': 'ridge', 'padding': '10px', 'backgroundColor': '#00008B'})]),
html.Div(style={'display': 'flex', 'justify-content': 'center'},
children=[html.Div(dcc.Graph(id='chart3'), style={'border': 'ridge', 'padding': '10px', 'backgroundColor': '#00008B'}),
html.Div(dcc.Graph(id='chart4'), style={'border': 'ridge', 'padding': '10px', 'backgroundColor': '#00008B'})])
...
@app.callback([Output(component_id='chart1', component_property='figure'),
Output(component_id='chart2', component_property='figure'),
Output(component_id='chart3', component_property='figure'),
Output(component_id='chart4', component_property='figure')],
[Input(component_id='dropdown-statistics',component_property='value'),
Input(component_id='select-year', component_property='value')])
...
return [html.Div(className='chart-grid', children=[html.Div(children=R_chart1),html.Div(children=R_chart2)], style={'display': 'flex'}),
html.Div(className='chart-grid', children=[html.Div(children=R_chart3),html.Div(children=R_chart4)], style={'display': 'flex'})]
elif (input_year and selected_statistics =='Yearly Statistics'):
yearly_data = data[data['Year'] == input_year]
...
return [html.Div(className='chart-grid', children=[html.Div(children=Y_chart1),html.Div(children=Y_chart2)], style={'display': 'flex'}),
html.Div(className='chart-grid', children=[html.Div(children=Y_chart3),html.Div(children=Y_chart4)], style={'display': 'flex'})]
因此,感谢工作人员的帮助,我能够修复错误。
将选项更改为 options=dropdown_options:
dcc.Dropdown (id='dropdown-statistics', 选项=下拉选项, value='选择统计数据', placeholder='选择报告类型', style={'textAlign': 'center', 'width': '80%', 'padding': 3, 'font-size': 20}) ]),
我删除了recession_data之后的yearly_data行。
图表中'Automobile_Sales' 和'Sales Volume' 之间的关键字不匹配。我都换了。
在 'yas' 中,我将 sum() 更改为 mean ():
yas= data.groupby('年份')['汽车_销售'].mean().reset_index()
我删除了带有 'mas' 的行:
Y_chart2 = dcc.Graph( 图=px.line(年度数据, x='月份', y='汽车销售', labels={'月份': '月份', 'Automobile_Sales': '汽车销售'}, title='每月汽车销售总额'))
我在 Y_chart3 中使用了 'Vehicle_Type' 而不是 'Year':
avr_vdata=yearly_data.groupby('Vehicle_Type')['Automobile_Sales'].mean().reset_index() Y_chart3 = dcc.Graph( 图=px.bar(avr_vdata, x='车辆类型', y='汽车销售', labels={'Vehicle_Type': '车辆类型', 'Automobile_Sales': '汽车销售'}, title='当年按车型划分的平均销量{}'.format(input_year)))