loading...
Cover image for Build COVID-19 Dashboard using Dash and Deploy to Google Cloud Platform

Build COVID-19 Dashboard using Dash and Deploy to Google Cloud Platform

rubiagatra profile image Doni Rubiagatra ・4 min read

Right now, We live in quarantine around the world. What we can do about it as a software engineer? We can make an interactive dashboard to help people understand the data. Why an interactive dashboard? Dynamic, interactive visualizations can empower people to explore the data for themselves.

Introducing Dash

Dash Demo

Build beautiful, web-based analytic apps.
No JavaScript required.

For the people that only have a data science background, learning web development is such intimidating work. Especially, learning a new programming language like Javascript. Being Python still has the best data science and machine learning ecosystem, creating web app visualization without hassle is a dream come true for Pythonistas.

Dash is a productive Python framework for building web applications. Written on top of Flask, Plotly.js, and React.js, Dash is ideal for building data visualization apps with highly custom user interfaces in pure Python. It's particularly suited for anyone who works with data in Python.

The COVID-19 Data

Thank you to my friend Odi that created COVID-19 API by Scraping ArcGIS on John Hopkins COVID-19 Dashboard. You can find the project below.

GitHub logo mathdroid / covid-19-api

COVID-19 global data (from JHU CSSE for now) as-a-service

COVID-19 API

Serving data from John Hopkins University CSSE as a JSON API

Deploy with ZEIT Now

Routes

  • /: contains opengraph image for sharing

  • /api: global summary

  • /api/og: generate a summary open graph image

  • /api/confirmed: global cases per region sorted by confirmed cases

  • /api/recovered: global cases per region sorted by recovered cases

  • /api/deaths: global cases per region sorted by death toll

  • /api/daily: global cases per day

  • /api/daily/[date]: detail of updates in a [date] (e.g. /api/daily/2-14-2020)

  • /api/countries: all countries and their ISO codes

  • /api/countries/[country]: a [country] summary (e.g. /api/countries/Indonesia or /api/countries/USA or /api/countries/CN)

  • /api/countries/[country]/confirmed: a [country] cases per region sorted by confirmed cases

  • /api/countries/[country]/recovered: a [country] cases per region sorted by recovered cases

  • /api/countries/[country]/deaths: a [country] cases per region sorted by death toll

  • /api/countries/[country]/og: generate a summary open graph image for a [country]

Usage

  1. Clone

    git clone --depth=1 https://github.com/mathdroid/covid-19-api
  2. Install deps (yarn, npm install)

  3. Install and register to ZEIT Now if you…

Before we get started, I hope you can follow this Dash tutorial for how to install and the basics stuff.

1. app.py

import dash

dash_app = dash.Dash(
        "An Example for Dash Apps",
        external_stylesheets=[
            "https://fonts.googleapis.com/css?family=Product+Sans:400,400i,700,700i",
            "https://cdn.rawgit.com/plotly/dash-app-stylesheets/2cc54b8c03f4126569a3440aae611bbef1d7a5dd/stylesheet.css",
            "https://codepen.io/bcd/pen/KQrXdb.css"
            ]
        )

dash_app.config.suppress_callback_exceptions = True

This is how you create a Dash app and for this example, you can use a custom CSS stylesheet to modify the default styles of the elements. dash_app.config.suppress_callback_exceptions = True We just want to ignore a warning exception.

2. template.py

import dash_html_components as html


def template(template_name: str, dropdown_menu):
    return html.Div([
        html.H2('An Example Dash App',
                    style={"display": "inline",
                        'font-size': '3.65em',
                        'margin-left': '7px',
                        'font-weight': 'bolder',
                        'font-family': 'Product Sans',
                        'color': "rgba(117, 117, 117, 0.95)",
                        'margin-top': '20px',
                        'margin-bottom': '0',
                            }),
                    html.Img(src="https://avatars2.githubusercontent.com/u/20743732",
                    style={
                        'height': '100px',
                        'float': 'right',
                        'margin-bottom': '10px',
                    }),
        dropdown_menu,
        html.Div(id='graphs-' + template_name)
    ], className='container')

There are two components that we will use more in a Dash app dash_html_components and dash_core_components. The dash_html_components library has a component for every HTML tag.

The html.H2('An Example Dash app') component generates a <h1>An Example Dash app</h1> HTML element in your application. You can add your custom CSS as dictionary style input argument.

In this code, we create a template function as a base of the page so it can be used on another function.

3. covid19.py

import dash_core_components as dcc
import plotly.graph_objs as go
from dash.dependencies import Input, Output
import pandas as pd

from apps import template
from apps.app import dash_app

APPS_NAME = 'covid19'
df = pd.read_json('https://covid19.mathdro.id/api/daily')
df['reportDate'] = pd.to_datetime(df['reportDate'])

dropdown_menu = dcc.Dropdown(id='data-input-' + APPS_NAME,
                            options=[ {'label': 'Data Harian Dunia', 'value': 'data-harian-dunia'}],
                            value=['data-harian-dunia'],
                            multi=True)

layout = template.template(APPS_NAME, dropdown_menu)

def covid19(value_name: str):
    data_1 = go.Scatter(x=df['reportDate'], y=df['totalConfirmed'], name="Total Confirmed", mode="lines+markers")
    data = [data_1]
    layout = dict(title='Total Positif Covid 19 di Seluruh Dunia',
                xaxis=dict(title='Hari'),
                yaxis=dict(title='Jumlah Kumulatif'),
    )
    fig = dict(data=data, layout=layout)
    return dcc.Graph(
        id=value_name,
        figure=fig,
    )

@dash_app.callback(
    Output('graphs-' + APPS_NAME, 'children'),
    [Input('data-input-' + APPS_NAME, 'value')],
)
def update_graph(data):
    graphs = []
    for x in data:
        if x == 'data-harian-dunia':
            graphs.append(covid19(x))

    return graphs

dash_core_components is a set of components for interactive user interfaces includes components like dropdowns, graphs, markdown blocks, and more.

As Python has a rich data science/machine learning ecosystem, you can just import pandas to get some data from API and transform it to the DataFrame and ready to manipulate the data.

The dash_app.callback decorator is how we can make the Dash app interactive. In Dash, the inputs and output of our application are simply the properties of a particular component.

4. main.py

import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output

from apps.app import dash_app
from apps import covid19

dash_app.layout = html.Div([
    dcc.Location(id='url', refresh=False),
    html.Div(id='page-content')
])

app = dash_app.server

@dash_app.callback(Output('page-content', 'children'),
              [Input('url', 'pathname')])
def display_page(pathname):
    if pathname == '/':
        return covid19.layout
    else:
        print(pathname)
        return '404'



if __name__ == '__main__':
    dash_app.run_server(host='0.0.0.0', debug=True, port=8080)

In main.py we create an interaction with the URL, you can add more pages by just add another layout on pathname. Dash apps are web applications. Dash uses Flask as a web framework. The underlying Flask app is available at dash_app.server. Also, you can use gunicorn to deploy your app by gunicorn -b 0.0.0.0:8080 main:app.

5. Google App Engine

And now, the final step is to deploy to the Google Cloud Platform using App Engine. You can learn to set up by this quickstart for Python 3. After that, you only have 2 steps to deploy the Dash Application.

Create app.yaml

runtime: python37

Just add the runtime, to tell the app engine to use Python 3 runtime for your application.

Just Deploy it

gcloud app deploy

Really simple right? by this, you can easily deploy your Dash Application to the world and not worrying about how the infrastructure goes into your apps.

This is an example Dash project, you can add your graph / or component as you wish. You can find the rest of the project and Speakerdeck by accessing these below.

Alt Text

GitHub logo rubiagatra / dash-covid19

An example for Dash Application

dash-covid19

An example for Dash Application

How to install

pip install -r requirements.txt

How to run

python main.py

Overview

img




Posted on Jun 2 by:

Discussion

markdown guide