8.4.1.Creating Dashboards with Plotly and Dash - sj50179/IBM-Data-Science-Professional-Certificate GitHub Wiki

Module Overview and Learning Objectives

As the saying goes, A picture worth thousand words. Data visualization through dashboards will help you uncover information from data that are hidden and democratize the understanding of the extracted information.

In this topic, you will create a dashboard with theme US Domestic Airline Flights Performance. You will do this using a US airline reporting carrier on-time performance dataset, plotly, and dash concepts learned throughout the course.

In this module, you will learn

  • How a dashboard can be used to answer critical business questions.
  • What high-level overview of popular dashboarding tools available in python.
  • How to use basic Plotly, plotly.graph_objects, and plotly express.
  • How to use Dash and basic overview of dash components (core and HTML).
  • How to add different elements (like text box, dropdown, graphs, etc) to the dashboard.
  • How to add interactivity to dash core and HTML components.

This module will help you get started with dashboard creation using the Plotly library. Hands-on labs will follow each concept to make you comfortable with using the library.

Reading lists will reference additional resources to learn more about the concepts covered.

Dashboarding Overview

Dashboard

  • Real-time visuals
  • Understand business moving parts
  • Visually track, analyze, and display key performance indicators (KPI)
  • Take informed decisions and improve performance
  • Reduced hours of analyzing

Best dashboards answer important business questions.

Scenario

Monitor and report US airline performance Requested report items

  1. Yop 10 airline carrier in year 2019 in terms of number of flights
  2. Number of flights in 2019 split by month
  3. Number of travelers from California (CA) to other states split by distance group

Introduction to Plotly

Plotly - An Overview

  • Interactive, open-source plotting library
  • Supports over 40 unique chart types
  • Includes chart types like statistical, financial, maps, scientific, and 3-dimensional
  • Visualizations can be displayed in Jupyter notebook, saved to HTML files, or can be used in developing Python-built web applications

Plotly Sub-modules

  • Plotly Graph Objects: Low-level interface to figures, traces, and layout

    plotly.graph_objects.Figure

  • Plotly Express: High-level wrapper

Using plotly.graph_objects

# Import required packages
import plotly.graph_objects as go
import plotly.express as px
import numpy as np

# Set random seed for reproducibility
np.random.seed(10)
x = np.arange(12)
# Create random y values
y = np.random.randint(50, 500, size=12)
# Line Plot using graph objects
# Plotly.graph contains a JSON object which has a structure of dict
# Here, 'go' is the plotly JSON object
# Updating values of 'go' object keywords, chart can be plotted
# Create figure and add trace (scatter)

fig = go.Figure(data=go.Scatter(x=x,y=y))
fig.update_layout(title='Simple Line Plot', xaxis_title='Month', yaxis_title='Sales')
fig.show()

  • Create the same line chart using Plotly express
# Entire line chart can be created in a single command
fig = px.line(x=x, y=y, title='Simple Line Plot', 
              labels=dict(x='Month', y='Sales'))
fig.show()

Additional Resources for Plotly

To learn more about using Plotly to create dashboards, explore

Plotly python

Plotly graph objects with example

Plotly express

API reference

Here are additional useful resources:

Plotly cheatsheet

Plotly community

Related blogs

Open-source datasets

Introduction to Dash

Dash - An Overview

  • Open-source User Interface Python library from Plotly
  • Easy to build GUI
  • Declarative and Reactive
  • Rendered in web browser and can be deployed to servers
  • Inherently cross-platform and mobile ready

Dash Components

  • Core components

    import dash_core_components as dcc

  • HTML components

    import dash_html_components as html

HTML Components

  • Component for every HTML tag
  • Keyword arguments describe the HTML attributes like style, className, and id

Core Components

  • Higher-level components that are interactive and are generated with JavaScript, HTML, and CSS through the React.js library
  • Example: Creating a slider, input area, check items, datepicker and so on

Additional Resources for Dash

To learn more about Dash, explore

Complete dash user guide

Dash core components

Dash HTML components

Dash community forum

Related blogs

Make dashboards interactive

Dash - Callbacks

  • Callback function is a python function that are automatically called by Dash whenever an input component's property changes.
  • **@acpp.callback**

Dash - Callback Function

@app.callback(Output, Input)
def callback_function
	.....
	.....
	.....
	return some_result

Callback with one input

# Import required packages
import pandas as pd
import plotly.express as px
import dash
import dash_html_components as html
import dash_core_components as dcc
from dash.dependencies import Input, Output

# Read the data
airlien_data = pd.read_csv('airline_2m.csv', encoding='ISO-8859-1',
			dtype={'Div1Airport': str, 'Div1TailNum': str,
                               'Div2Airport': str, 'Div2TailNum': str})
app = dash.Dash()
#Design dash app layout
app.layout = html.Div(children=[html.H1('Airline Dashboard',
				style={'textAlign': 'Center', 'color': colors['text'],	
                                       'font-size': 40}),
                                html.Div(['Input: ', dcc.Input(id='input-yr', value='2010',
                                                     type='number', style={'height':'50px', 'font-size': 35}).],
                                                     style={'font-size': 40}), 
                                html.Br(),
                                html.Br(),
                                html.Div(dcc.Graph(id='bar-plot')),
                      ])
@app.callback(Output(component_id='bar-plot', component_property='figure'),
	      Input(compoenent_id='input-yr', component_property='value'))

def get_graph(entered_year):
    # Select data
    df = airline_data[airline_data['Year']==int(entered_year)]
    # Top 10 airline carrier in terms of number of flights
    g1 = df.groupby(['Reporting_Airline'])['Flights'].sun().nlargest(10).reset_index()
    # Plot the graph
    fig1 = px.bar(g1, x='Reporting_Airline', y='Flights', 
                  title='Top 10 airline carrier in year' + str(entered_year) 
                  + ' in terms of number of flights')
    fig1.update_layout()
    return fig1
if __name__ == '__main__':
    app.num_server(port=8002, host='127.0.0.1', debug=True)

Callback with two inputs

app = dash.Dash()
#Design dash app layout
app.layout = html.Div(children=[html.H1('Airline Dashboard',
                                style={'textAlign': 'Center', 'color': colors['text'],
                                       'font-size': 40}),
                                html.Div(['Year: ', dcc.Input(id='input-yr', value='2010',
                                          type='number', style={'height':'50px', 'font-size': 35}).],
                                          style={'font-size': 40}),
                                html.Div(['State Abbreviation: ', 
                                          dcc.Input(id='input-ab', value='AL',
                                          type='text', style={'height':'50px', 'font-size': 35}),],
                                          style={'font-size': 40}),
                                html.Br(),
                                html.Br(),
                                html.Div(dcc.Graph(id='bar-plot')),
                       ])
@app.callback(Output(component_id='bar-plot', component_property='figure'),
             [Input(compoenent_id='input-yr', component_property='value'),
              Input(compoenent_id='input-ab', component_property='value')])

def get_graph(entered_year, entered_state):
    # Select data
    df = airline_data[(airline_data['Year']==int(entered_year) &
                      (airline_data['OriginState']==entered_state)]
    # Top 10 airline carrier in terms of number of flights
    g1 = df.groupby(['Reporting_Airline'])['Flights'].sun().nlargest(10).reset_index()
    # Plot the graph
    fig1 = px.bar(g1, x='Reporting_Airline', y='Flights',  
                  title='Top 10 airline carrier in year' + str(entered_year) 
                  + ' in terms of number of flights')
    fig1.update_layout()
    return fig1
if __name__ == '__main__':
    app.num_server(port=8002, host='127.0.0.1', debug=True)

References

Additional Resources for Interactive Dashboards

To learn more about making interactive dashboards in Dash, visit

Python decorators reference 1

Python decorators reference 2

Callbacks with example

Dash app gallery

Dash community components

Lesson Summary

  • Best dashboards answer critical business questions. It will help business make informed decisions, thereby improving performance.
  • Dashboards can produce real-time visuals.
  • Plotly is an interactive, open-source plotting library that supports over 40 chart types.
  • The web based visualizations created using Plotly python can be displayed in Jupyter notebook, saved to standalone HTML files, or served as part of pure Python-built web applications using Dash.
  • Plotly Graph Objects is the low-level interface to figures, traces, and layout whereas plotly express is a high-level wrapper for Plotly.
  • Dash is an Open-Source User Interface Python library for creating reactive, web-based applications. It is both enterprise-ready and a first-class member of Plotly’s open-source tools.
  • Core and HTML are the two components of dash.
  • The dash_html_components library has a component for every HTML tag.
  • The dash_core_components describe higher-level components that are interactive and are generated with JavaScript, HTML, and CSS through the React.js library.
  • A callback function is a python function that is automatically called by Dash whenever an input component's property changes. Callback function is decorated with @app.callback decorator.
  • Callback decorator function takes two parameters: Input and Output. Input and Output to the callback function will have component id and component property. Multiple inputs or outputs should be enclosed inside either a list or tuple.