A Dashboard Project- Section 2
Components of the Dashboard
- Select Region
- Select Year
- Divison to display
- Pie Chart to display Monthly Average Estimated Fire Area for the selected Regions in the selected Year
- Bar Chart to display Monthly Average Count of Pixels for Presumed Vegetation Fires for the selected Regions in the selected Year
Requirements to create the expected result
- A dropdown menu: For choosing year
2. A radioitem for choosing the Region
3. The layout will be designed as follows:
- An outer division with two inner divisions
- One of the inner divisions will have information about the radioitem and dropdown (which are the input) and the other one is for adding graphs (two output graphs).
- Callback function to compute data, create graph and return to the layout.
Steps of Building Dashboard:
Import required libraries and read the dataset. Copy and paste the below command to the terminal.
pip3.8 install setuptools
python3.8 -m pip install packaging
python3.8 -m pip install pandas dash
pip3 install httpx==0.20 dash plotly
The skeleton of the application contains:
- Import the library code
import pandas as pd
import dash
from dash import html, dcc
from dash.dependencies import Input, Output, State
import plotly.graph_objects as go
import plotly.express as px
from dash import no_update
import datetime as dt
- Create app
app = dash.Dash(__name__)
- Clear the layout and do not display exception till callback gets executed
app.config.suppress_callback_exceptions = True
- Read the wildfire data into pandas dataframe
df = pd.read_csv('https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-DV0101EN-SkillsNetwork/Data%20Files/Historical_Wildfires.csv')
- Extract year and month from the date column
df['Month'] = pd.to_datetime(df['Date']).dt.month_name() #used for the names of the months
df['Year'] = pd.to_datetime(df['Date']).dt.year
- Layout Section of Dash
Step 1: Add the Title to the Dashboard using HTML H1 component
app.layout = html.H1('Australia Wildfire Dashboard',
style={'textAlign': 'center', 'color': '#503D36',
'font-size': 26}),
Step 2: Add a radioitem using dcc.RaioItems and dropdown using dcc.dropdown (Please scroll right to see the whole code)
#outer division starts
html.Div([
# First inner divsion for adding dropdown helper text for Selected Drive wheels
html.Div([
html.H2('Select Region:', style={'margin-right': '2em'}),
#Radio items to select the region
dcc.RadioItems(['NSW','QL','SA','TA','VI','WA'], 'NSW', id='region',inline=True)]),
#Radio items to select the region
#dcc.RadioItems(['NSW',.....], value ='...', id='...',inline=True)]),
#OR you can use labels:value pair a well in raioditems as below
#Radio items to select the region
dcc.RadioItems([{"label":"New South Wales","value": "NSW"},
{"label":"Northern Territory","value": "NT"},
{"label":"Queensland","value": "QL"},
{"label":"South Australia","value": "SA"},
{"label":"Tasmania","value": "TA"},
{"label":"Victoria","value": "VI"},
{"label":"Western Australia","value": "WA"}],"NSW", id='region',inline=True)]),
#Dropdown to select year
html.Div([
html.H2('Select Year:', style={'margin-right': '2em'}),
dcc.Dropdown(df.Year.unique(), value = 2005,id='year')
#notice the use of unique() from pandas to fetch the values of year from the dataframe for dropdown
]),
Step 3: Add two empty divisions for output inside the next inner division.
html.Div([
html.Div([ ], id='plot1'),
html.Div([ ], id='plot2')
], style={'.........}),
])
#outer division ends
Step 4: Add the Output and input components inside the app.callback decorator. (What do you mean by decorator?)
The inputs and outputs of our application’s interface are described declaratively as the arguments of @app.callback decorator.
- In Dash, the inputs and outputs of our application are simply the properties of a particular component. (In this example, we have two inputs: Input for Region is the value property of the component that has the ID region and input for Year is the value property of the component that has the ID year Our layout has 2 outputs so we need to create 2 output components.)
@app.callback([Output(component_id='plot1', component_property='children'),
Output(component_id='plot2', component_property='children')],
[Input(component_id='region', component_property='value'),
Input(component_id='year', component_property='value')])
Step 5: Add the callback function
- Whenever an input property changes, the function reg_year_display() that the callback decorator wraps will get called automatically.
- The function first filters our dataframe
df
by the selected value of the region from the radio items and year from the dropdown as follows
region_data = df[df['Region'] == input_region]
y_r_data = region_data[region_data['Year']==input_year]
- For pie chart on Monthly Average Estimated Fire Area:
est_data = y_r_data.groupby('Month')['Estimated_fire_area'].mean().reset_index()
fig1 = px.pie(est_data, values='Estimated_fire_area', names='Month', title="{} : Monthly Average Estimated Fire Area in year {}".format(input_region,input_year))
- For bar chart on Monthly Average Count of Pixels for Presumed Vegetation Fires: -
veg_data = y_r_data.groupby('Month')['Count'].mean().reset_index()
fig2 = px.bar(veg_data, x='Month', y='Count', title='{} : Average Count of Pixels for Presumed Vegetation Fires in year {}'.format(input_region,input_year))
- Finally we return the 2 figure objects
return [dcc.Graph(figure=fig1),
dcc.Graph(figure=fig2) ]
Step 6: And the last Let’s run our app. Write the below code to your command
python3.8 Dash_wildfire.py
Observe the port number shown in the terminal and press the link
And our interactive dashboard is here.
References:
Source Code of the project https://github.com/sametgirgin/DashBoardCheatSheet/blob/main/Dash_wildfire.py