Need help with Dash Plotly

Hello, I’m having some troubles with my code. When I try to visualize it it doesn’t display anything, just “error loading layout”. I don’t know where is my error.

This is my code:

#!/usr/bin/env python
# coding: utf-8

# In[ ]:


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"

#---------------------------------------------------------------------------------
# Create the dropdown menu options
dropdown_options = [
    {'label': 'Yearly Statistics', '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([
    #TASK 2.1 Add title to the dashboard
    html.H1("Automobile 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=dropdown_options,
            value='Select Statistics',
            placeholder='Select a report type',
            style={'width': '80%', 'padding': 3, 'text-align-last': 'center', 'font-size': 20}
        )
    ]),
    html.Div(dcc.Dropdown(
            id='select-year',
            options=[{'label': i, 'value': i} for i in year_list],
            value="Select Year",
            style={'width': '80%', 'padding': 3, 'text-align-last': 'center', 'font-size': 20}
        )),
    html.Div([#TASK 2.3: Add a division for output display
    html.Div(id='output-container', className='chart-grid', style={"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_year, 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='select-year', component_property='value'), 
    Input(component_id='dropdown-statistics', component_property='value')])


def update_output_container(selected_year, selected_statistics):
    if selected_statistics == 'Recession Period Statistics':
        # Filter the data for recession periods
        recession_data = data[data['Recession'] == 1]
        
#TASK 2.5: Create and display graphs for Recession Report Statistics

#Plot 1 Automobile sales fluctuate over Recession Period (year wise)
        # use groupby to create relevant data for plotting
        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 Calculate the average number of vehicles sold by vehicle type       
        # use groupby to create relevant data for plotting
        avg_sales = recession_data.groupby('Vehicle_Type')['Automobile_Sales'].mean().reset_index()                           
        R_chart2  = dcc.Graph( 
                        figure=px.bar(avg_sales, 
                        x="Vehicle_Type",
                        y="Automobile_Sales", 
                        title="Average Automobile Sales by Vehicle Type in Recession Period"))
        
# Plot 3 Pie chart for total expenditure share by vehicle type during recessions
        # use groupby to create relevant data for plotting
        exp_rec= recession_data.groupby('Vehicle_Type')['Advertising_Expenditure'].mean().reset_index()
        R_chart3 = dcc.Graph(
                    figure=px.pie(exp_rec,
                    values='Advertising_Expenditure',
                 names='Vehicle_Type',
                 title="Expenditures shared by vehicle type during recessions"
                )
        )

# Plot 4 bar chart for the effect of unemployment rate on vehicle type and sales
        ur = recession_data.groupby('unemployment_rate')['Automobile_Sales'].mean().reset_index()
        figure=px.bar(ur,
            x='unemployment_rate',
            y='Automobile_Sales',
            title="Effects of Unemployment Rate on Automobile Sales by Vehicle Type during Recession Period")


        return [
                html.Div(className='chart-item', children=[html.Div(children=R_chart1),html.Div(children=R_chart2)],style={'display': 'flex'}),
                html.Div(className='chart-item', children=[html.Div(children=R_chart3),html.Div(children=R_chart4)],style={'display': 'flex'})
                ]

# TASK 2.6: Create and display graphs for Yearly Report Statistics
 # Yearly Statistic Report Plots                             
    elif (input_year and selected_statistics=='Yearly Statistics') :
        yearly_data = data[data['Year'] == selected_year]
                              
#TASK 2.5: Creating Graphs Yearly data
                              
#plot 1 Yearly Automobile sales using line chart for the whole period.
        yas= data.groupby('Year')['Automobile_Sales'].mean().reset_index()
        Y_chart1 = dcc.Graph(figure=px.line(yas, 
                                    x="Year",
                                    y="Automobile_Sales",
                                    title="Automobile Sales in the Year"))
            
# Plot 2 Total Monthly Automobile sales using line chart.
        data['Month'] = pd.to_datetime(data['Month'])
        mas = yearly_data.groupby('Month')['Automobile_Sales'].sum().reset_index()
        Y_chart2 = dcc.Graph(figure=px.line(mas,
                                        x='Month',
                                    y='Automobile_Sales',
                                    title='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_data, x="Year", y="Automobile_Sales",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 Advertising Expenditure by Vehicle Type'))

#TASK 2.6: Returning the graphs for displaying Yearly data
        return [
                html.Div(className='chart-item', children=[html.Div(children=Y_chart1),html.Div(children=Y_chart2)],style={'display': 'flex'}),
            html.Div(className='chart-item', 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)

I hope someone can help me

  1. Initial Dropdown Values: The initial value set for both dropdowns (‘Select Statistics’ and ‘Select Year’) does not match any of the options values in your dropdowns. The value should match one of the options values or be None if you want the dropdown to start with no selection. Also, ‘Select Year’ is not an integer like the rest of the options in the year_list dropdown. Either replace with an actual value relating to dropdown_options or remove it and use placeholder='Select Statistics'
  2. Missing Callbacks: While your layout includes components that would typically interact with callbacks (like updating a graph based on dropdown selections), the actual callbacks are missing. You need to add them to make the app interactive.
  3. Styling Issue in html.Div for Output Container: The style you’ve assigned to the output container (style={"flex"}) is incomplete. The property “flex” usually requires a value like style={"display": "flex"} to correctly apply flexbox styling.

I’d also suggest taking a look at update_output_container and update accordingly, specifically the avr_data and input_year are not setup correctly.

1 Like

I made some huge changes, but still cannot find some troubles

#!/usr/bin/env python
# coding: utf-8

# In[ ]:


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"

#---------------------------------------------------------------------------------
# Create the dropdown menu options
dropdown_options = [
    {'label': 'Yearly Statistics', '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([
    #TASK 2.1 Add title to the dashboard
    html.H1("Automobile 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='Recession Period Statistics',
            placeholder='Select a report type',
            style={'width': '80%', 'padding': 3, 'text-align-last': 'center', 'font-size': 20}
        )
    ]),
    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': 3, 'text-align-last': 'center', 'font-size': 20}
        )),
    html.Div([#TASK 2.3: Add a division for output display
    html.Div(id='output-container', className='chart-grid', style={"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':
        # Filter the data for recession periods
        recession_data = data[data['Recession'] == 1]
        yearly_data = data[data['Year'] == input_year]
        
#TASK 2.5: Create and display graphs for Recession Report Statistics

#Plot 1 Automobile sales fluctuate over Recession Period (year wise)
        # use groupby to create relevant data for plotting
        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 Calculate the average number of vehicles sold by vehicle type       
        # use groupby to create relevant data for plotting
        avg_sales = recession_data.groupby('Vehicle_Type')['Automobile_Sales'].mean().reset_index()                           
        R_chart2  = dcc.Graph( 
                        figure=px.bar(avg_sales, 
                        x="Vehicle_Type",
                        y="Automobile_Sales", 
                        title="Average Automobile Sales by Vehicle Type in Recession Period"))
        
# Plot 3 Pie chart for total expenditure share by vehicle type during recessions
        # use groupby to create relevant data for plotting
        exp_rec= recession_data.groupby('Vehicle_Type')['Advertising_Expenditure'].mean().reset_index()
        R_chart3 = dcc.Graph(
                    figure=px.pie(exp_rec,
                    values='Advertising_Expenditure',
                 names='Vehicle_Type',
                 title="Expenditures shared by vehicle type during recessions"
                )
        )

# Plot 4 bar chart for the effect of unemployment rate on vehicle type and sales
        ur = recession_data.groupby('unemployment_rate')['Automobile_Sales'].mean().reset_index()
        figure=px.bar(ur,
            x='unemployment_rate',
            y='Automobile_Sales',
            title="Effects of Unemployment Rate on Automobile Sales by Vehicle Type during Recession Period")


        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'})
                ]

# TASK 2.6: Create and display graphs for Yearly Report Statistics
 # Yearly Statistic Report Plots                             
    elif (input_year and selected_statistics=='Yearly Statistics') :
        yearly_data = data[data['Year'] == selected_year]
                              
#TASK 2.5: Creating Graphs Yearly data
                              
#plot 1 Yearly Automobile sales using line chart for the whole period.
        yas= data.groupby('Year')['Automobile_Sales'].mean().reset_index()
        Y_chart1 = dcc.Graph(figure=px.line(yas, 
                                    x="Year",
                                    y="Automobile_Sales",
                                    title="Automobile Sales in the Year"))
            
# Plot 2 Total Monthly Automobile sales using line chart.
        data['Month'] = pd.to_datetime(data['Month'])
        mas = yearly_data.groupby('Month')['Automobile_Sales'].sum().reset_index()
        Y_chart2 = dcc.Graph(figure=px.line(mas,
                                        x='Month',
                                    y='Automobile_Sales',
                                    title='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_data, x="Year", y="Automobile_Sales",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 Advertising Expenditure by 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)


You need to rebuild this, start with this code and work your way out again.

import dash
from dash import dcc, 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"

# ---------------------------------------------------------------------------------
# Create the dropdown menu options
dropdown_options = [
    {'label': 'Yearly Statistics', 'value': 'Yearly'},
    {'label': 'Recession Period Statistics', 'value': 'Recession'}
]
# 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 Statistics Dashboard", style={"textAlign": "center", "color": "#503D36", "font-size": 24}),
    html.Div([
        html.Label("Select Statistics:"),
        dcc.Dropdown(
            id='dropdown-statistics',
            options=dropdown_options,
            value='Yearly',  # Set to the first option's value
            placeholder='Select a report type',
            style={'width': '80%', 'padding': 3, 'text-align-last': 'center', 'font-size': 20}
        )
    ]),
    html.Div(dcc.Dropdown(
        id='select-year',
        options=[{'label': i, 'value': i} for i in year_list],
        value=1980,  # Set to the first year in the list
        style={'width': '80%', 'padding': 3, 'text-align-last': 'center', 'font-size': 20}
    )),
    html.Div(id='output-container', className='chart-grid', style={"display": "flex"})
])

# Dummy callback to demonstrate interaction
@app.callback(
    Output('output-container', 'children'),
    [Input('dropdown-statistics', 'value'),
     Input('select-year', 'value')]
)
def update_output(statistics_type, selected_year):
    # Placeholder content, replace with your actual update logic
    return html.Div([
        html.H4(f"Selected Statistics: {statistics_type}"),
        html.H4(f"Selected Year: {selected_year}")
    ])



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

Thanks, the layout is now displayed, now I will fix other issues. Thank you so much!

1 Like

Hey! I almost got it. Can you please check if everything its okay?

#!/usr/bin/env python
# coding: utf-8

# In[ ]:


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"

#---------------------------------------------------------------------------------
# Create the dropdown menu options
dropdown_options = [
    {'label': 'Yearly Statistics', '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([
    #TASK 2.1 Add title to the dashboard
    html.H1("Automobile 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=dropdown_options,
            value='Select Statistics',
            placeholder='Select a report type',
            style={'width': '80%', 'padding': 3, 'text-align-last': 'center', 'font-size': 20}
        )
    ]),
    html.Div(dcc.Dropdown(
        id='select-year',
        options=[{'label': i, 'value': i} for i in year_list],
        value="Select Year",  # Set to the first year in the list
        style={'width': '80%', 'padding': 3, 'text-align-last': 'center', 'font-size': 20}
    )),
    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':
        # Filter the data for recession periods
        recession_data = data[data['Recession'] == 1]
        yearly_data = data[data['Year'] == input_year]
        
#TASK 2.5: Create and display graphs for Recession Report Statistics

#Plot 1 Automobile sales fluctuate over Recession Period (year wise)
        # use groupby to create relevant data for plotting
        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 Calculate the average number of vehicles sold by vehicle type       
        # use groupby to create relevant data for plotting
        avg_sales = recession_data.groupby('Vehicle_Type')['Automobile_Sales'].mean().reset_index()                           
        R_chart2  = dcc.Graph( 
                        figure=px.bar(avg_sales, 
                        x="Vehicle_Type",
                        y="Automobile_Sales", 
                        title="Average Automobile Sales by Vehicle Type in Recession Period"))
        
# Plot 3 Pie chart for total expenditure share by vehicle type during recessions
        # use groupby to create relevant data for plotting
        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="Expenditures shared by vehicle type during recessions"))

# Plot 4 bar chart for the effect of unemployment rate on vehicle type and sales
        unemp_rate = recession_data.groupby('unemployment_rate')['Automobile_Sales'].mean().reset_index()
        R_chart4 = dcc.Graph(
            figure=px.bar(unemp_rate,
            x='unemployment_rate',
            y='Automobile_Sales',
            title="Effects of Unemployment Rate on Automobile Sales by Vehicle Type during Recession Period"))


        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'})
                ]

# TASK 2.6: Create and display graphs for Yearly Report Statistics
 # Yearly Statistic Report Plots                             
    elif (input_year and selected_statistics=='Yearly Statistics') :
        yearly_data = data[data['Year'] == input_year]
                              
#TASK 2.5: Creating Graphs Yearly data
                              
#plot 1 Yearly Automobile sales using line chart for the whole period.
        yas= data.groupby('Year')['Automobile_Sales'].mean().reset_index()
        Y_chart1 = dcc.Graph(
            figure=px.line(yas, 
                x="Year",
                y="Automobile_Sales",
                title="Automobile Sales in the Year"))
            
# Plot 2 Total Monthly Automobile sales using line chart.
        mas = yearly_data.groupby('Month')['Automobile_Sales'].sum().reset_index()
        Y_chart2 = dcc.Graph(
            figure=px.line(mas,
                x='Month',
                y='Automobile_Sales',
                title='Monthly Automobile Sales'))

            # Plot bar chart for average number of vehicles sold during the given year
        avr_data=yearly_data.groupby('Vehicle_Type')['Automobile_Sales'].mean().reset_index()
        Y_chart3 = dcc.Graph(
            figure=px.bar(avr_data, 
                x="Vehicle_Type", 
                y="Automobile_Sales",
                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 Advertising Expenditure by 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)


UPDATE: I already submit my homework , everything worked as expected, I got an “A”, 10/10. Thank you so much for your help and advice.

1 Like

You did good, the only issue I have with your code is the styling. The majority of traffic is mobile so always build an application thats dynamic and could fit many size screens. Try this code and compare it with what you have:

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
import dash_mantine_components as dmc

# 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"

# ---------------------------------------------------------------------------------
# Create the dropdown menu options
dropdown_options = [
    {"label": "Yearly Statistics", "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(
    [
        # TASK 2.1 Add title to the dashboard
        html.H1(
            "Automobile Statistics Dashboard",
            style={"textAlign": "center", "color": "#503D36", "font-size": 24},
        ),
        html.Div(
            [  # TASK 2.2: Add two dropdown menus
                html.Label("Select Statistics:"),
                dmc.Stack(
                    [
                        dcc.Dropdown(
                            id="dropdown-statistics",
                            options=dropdown_options,
                            value="Select Statistics",
                            placeholder="Select a report type",
                            style={
                                "width": "100%",
                                "padding": 3,
                                "text-align-last": "center",
                                "font-size": 20,
                            },
                        ),
                        dcc.Dropdown(
                            id="select-year",
                            options=[{"label": i, "value": i} for i in year_list],
                            value="Select Year",
                            style={
                                "width": "100%",
                                "padding": 3,
                                "text-align-last": "center",
                                "font-size": 20,
                            },
                        ),
                    ],
                    style={
                        "display": "flex",
                        "justify-content": "center",
                        "align-items": "center",
                        "width": "100%",
                    },
                ),
            ]
        ),
        html.Div(
            id="output-container",
            className="chart-grid",
        ),
    ]
)


# 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":
        # Filter the data for recession periods
        recession_data = data[data["Recession"] == 1]
        yearly_data = data[data["Year"] == input_year]

        # TASK 2.5: Create and display graphs for Recession Report Statistics

        # Plot 1 Automobile sales fluctuate over Recession Period (year wise)
        # use groupby to create relevant data for plotting
        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 Calculate the average number of vehicles sold by vehicle type
        # use groupby to create relevant data for plotting
        avg_sales = (
            recession_data.groupby("Vehicle_Type")["Automobile_Sales"]
            .mean()
            .reset_index()
        )
        R_chart2 = dcc.Graph(
            figure=px.bar(
                avg_sales,
                x="Vehicle_Type",
                y="Automobile_Sales",
                title="Average Automobile Sales by Vehicle Type in Recession Period",
            )
        )

        # Plot 3 Pie chart for total expenditure share by vehicle type during recessions
        # use groupby to create relevant data for plotting
        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="Expenditures shared by vehicle type during recessions",
            ),
        )

        # Plot 4 bar chart for the effect of unemployment rate on vehicle type and sales
        unemp_rate = (
            recession_data.groupby("unemployment_rate")["Automobile_Sales"]
            .mean()
            .reset_index()
        )
        R_chart4 = dcc.Graph(
            figure=px.bar(
                unemp_rate,
                x="unemployment_rate",
                y="Automobile_Sales",
                title="Effects of Unemployment Rate on Automobile Sales by Vehicle Type during Recession Period",
            )
        )

        # TASK 2.5: Returning the graphs for displaying Recession data
        R_layout = dmc.Container(
            [
                dmc.Grid(
                    children=[
                        dmc.Col(
                            html.Div(R_chart1, style={"width": "100%"}), md=6, sm=12
                        ),
                        dmc.Col(
                            html.Div(R_chart2, style={"width": "100%"}), md=6, sm=12
                        ),
                    ],
                    gutter="xl",
                ),
                dmc.Grid(
                    children=[
                        dmc.Col(
                            html.Div(R_chart3, style={"width": "100%"}), md=6, sm=12
                        ),
                        dmc.Col(
                            html.Div(R_chart4, style={"width": "100%"}), md=6, sm=12
                        ),
                    ],
                    gutter="xl",
                ),
            ]
        )

        return R_layout

    # TASK 2.6: Create and display graphs for Yearly Report Statistics
    # Yearly Statistic Report Plots
    elif input_year and selected_statistics == "Yearly Statistics":
        yearly_data = data[data["Year"] == input_year]

        # TASK 2.5: Creating Graphs Yearly data

        # plot 1 Yearly Automobile sales using line chart for the whole period.
        yas = data.groupby("Year")["Automobile_Sales"].mean().reset_index()
        Y_chart1 = dcc.Graph(
            figure=px.line(
                yas,
                x="Year",
                y="Automobile_Sales",
                title="Automobile Sales in the Year",
            )
        )

        # Plot 2 Total Monthly Automobile sales using line chart.
        mas = yearly_data.groupby("Month")["Automobile_Sales"].sum().reset_index()
        Y_chart2 = dcc.Graph(
            figure=px.line(
                mas, x="Month", y="Automobile_Sales", title="Monthly Automobile Sales"
            ),
        )

        # Plot bar chart for average number of vehicles sold during the given year
        avr_data = (
            yearly_data.groupby("Vehicle_Type")["Automobile_Sales"].mean().reset_index()
        )
        Y_chart3 = dcc.Graph(
            figure=px.bar(
                avr_data,
                x="Vehicle_Type",
                y="Automobile_Sales",
                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 Advertising Expenditure by Vehicle Type",
            ),
        )

        # TASK 2.5: Returning the graphs for displaying Recession data
        Y_layout = dmc.Container(
            [
                dmc.Grid(
                    children=[
                        dmc.Col(
                            html.Div(Y_chart1, style={"width": "100%"}), md=6, sm=12
                        ),
                        dmc.Col(
                            html.Div(Y_chart2, style={"width": "100%"}), md=6, sm=12
                        ),
                    ],
                    gutter="xl",
                ),
                dmc.Grid(
                    children=[
                        dmc.Col(
                            html.Div(Y_chart3, style={"width": "100%"}), md=6, sm=12
                        ),
                        dmc.Col(
                            html.Div(Y_chart4, style={"width": "100%"}), md=6, sm=12
                        ),
                    ],
                    gutter="xl",
                ),
            ]
        )
        return Y_layout

    else:
        return dash.no_update


# Run the Dash app
if __name__ == "__main__":
    app.run_server(debug=True, port=5111)

Refrence:

https://dash-bootstrap-components.opensource.faculty.ai/docs/components/layout/