[PYTHON] Create a layout by combining Dash and Bootstrap

It also serves as a memorandum for amateurs. Please pardon.

Last time https://qiita.com/Naoya_Study/items/507cf063a9300e9e41f6

Today's completed form is here ↓ ↓

3s39m-g3lc1.gif

1. Install Dash Bootstrap Components

There is a library that allows you to use Bootstrap within the Python framework Dash. This time I will use it to make a very simple 2x2 layout.

The library used is Dash Bootstrap Components. https://dash-bootstrap-components.opensource.faculty.ai/ Install it.

pip install dash-bootstrap-components

The basic template looks like this. Create a layout by adding elements to dbc.Container.

import dash
import dash_bootstrap_components as dbc

app = dash.Dash(external_stylesheets=[dbc.themes.BOOTSTRAP])

app.layout = dbc.Container("""I will add various elements here""")

if __name__ == "__main__":
    app.run_server(debug=True)

2. Make a simple layout

Now let's actually write a 2x2 layout.

import dash
import dash_bootstrap_components as dbc
import dash_html_components as html

app = dash.Dash(external_stylesheets=[dbc.themes.BOOTSTRAP])

app.layout = dbc.Container(
    [   dbc.Row(
            [
                dbc.Col(
                    html.H1("Title here!"),
                    style={"background-color": "pink"}
                    )
            ],
            className="h-30"
        ),
        dbc.Row(
            [
                dbc.Col(
                    html.P("world map!"),
                    width=7,
                    style={"height": "100%", "background-color": "red"},
                ),
                dbc.Col(
                    html.P("List of infected people by country!"),
                    width=5,
                    style={"height": "100%", "background-color": "green"},
                ),
            ],
            className="h-50"
        ),
        dbc.Row(
            [
                dbc.Col(
                    html.P("Map of Japan!"),
                    width=7,
                    style={"height": "100%", "background-color": "blue"},
                ),
                dbc.Col(
                    html.P("Bar graph of changes in the number of infected people in Japan!"),
                    width=5,
                    style={"height": "100%", "background-color": "cyan"},
                ),
            ],
            className="h-50",
        ),
    ],
    style={"height": "90vh"},
)

if __name__ == "__main__":
    app.run_server(debug=True)

layout.PNG
className="h-50"

This 50 means 50 percent of the height.

style={"height": "90vh"}

vh stands for "viewport height" and means 90% of the screen height (maybe)

3. Insert the graph

We will insert the previously created figure according to this layout. Basically just replace html.P () with the created dcc.Graph ().

#rewrite
html.P()
↓
dcc.Graph()
import dash
import dash_bootstrap_components as dbc
import dash_html_components as html
import requests, io, re
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
from datetime import datetime as dt
import dash_table
import dash_core_components as dcc
from corona_def import Get_Df, Df_Merge, Df_Count_by_Date, Df_Globe_Merge

app = dash.Dash(external_stylesheets=[dbc.themes.BOOTSTRAP])

app.layout = dbc.Container(
    [  dbc.Row(
            [
                dbc.Col(
                    html.H1("Novel Coronavirus (COVID-19) Situation"),
                    style = {
                        "size": "30px",
                        "background-color": "#1b1935",
                        "color": "white",
                        "textAlign": "center",
                        }
                    )
            ],
            className = "h-30"
        ),
        dbc.Row(
            [
                dbc.Col(
                    html.H4("Number of infected people in the world"),
                    width = 7,
                    style = {
                        "height": "100%",
                        "background-color": "white",
                        "textAlign": "left",
                        "padding": "10px"
                        },
                ),
                dbc.Col(
                    html.H4(""),
                    width = 5,
                    style = {
                        "height": "100%",
                        "background-color": "white",
                        "textAlign": "center"
                        },
                ),
            ],
            className = "h-8"
        ),
        dbc.Row(
            [
                dbc.Col(
                        dcc.Graph(
                            id = 'WorldMap',
                            figure = {
                                'data' : [
                                    go.Choropleth(
                                        locations = df_globe_merge['code'],
                                        z = df_globe_merge['Confirmed'],
                                        text = df_globe_merge['COUNTRY'],
                                        colorscale = 'Plasma',
                                        marker_line_color ='darkgray',
                                        marker_line_width = 0.5,
                                        colorbar_title = 'Number of infected people',
                                    )
                                ],
                                'layout' : go.Layout(
                                    template = "ggplot2",
                                    width = 600,
                                    height = 270,
                                    title = {
                                        'font': {'size': 25},
                                        'y': 0.9,
                                        'x': 0.5,
                                        'xanchor': 'center',
                                        'yanchor': 'top'
                                        },
                                    margin={'b': 5, 'l': 5, 'r': 5, 't': 5},
                                    geo={"projection_type": 'equirectangular'}
                                )
                            }
                        ),
                    width = 7,
                    style = {
                        "height": "100%",
                        "background-color": "white",
                        "border-color": "white",
                        "border-width":"10px"
                        },
                ),
                dbc.Col(
                    dash_table.DataTable(
                        columns = [{"name": i, "id": i} for i in df_globe.columns],
                        data = df_globe.to_dict('records'),
                        style_header = {'backgroundColor': '#eae6e8'},
                        style_cell = {
                                'backgroundColor': '#fbf9f7',
                                'color': 'black',
                                'font-size': '15px',
                                'textAlign': 'center'
                                },
                        style_table = {
                                'maxHeight': '300px',
                                'overflowY': 'scroll',
                                'overflowX': 'hidden',
                                },
                        ),
                    width = 5,
                    style = {"height": "100%"}
                ),
            ],
            className = "h-50"
        ),
        dbc.Row(
            [
                dbc.Col(
                    html.H4("Domestic infected person distribution"),
                    width = 7,
                    style = {
                        "height": "100%",
                        "background-color": "white",
                        "textAlign": "left",
                        "padding":"10px"
                        },
                ),
                dbc.Col(
                    html.H4("Cumulative number of infected people in Japan"),
                    width = 5,
                    style = {
                        "height": "100%",
                        "background-color": "white",
                        "textAlign": "left",
                        "padding":"13px"
                        },
                ),
            ],
            className = "h-30"
        ),
        dbc.Row(
            [
                dbc.Col(
                        dcc.Graph(
                            id = 'JapMap',
                            figure = {
                                'data' : [
                                    go.Scattergeo(
                                        lat = df_merge["latitude"],
                                        lon = df_merge["longitude"],
                                        mode = 'markers',
                                        marker = {
                                            "color": 'red',
                                            "size": df_merge['China']/5+6,
                                            "opacity": 0.8,
                                            "reversescale": True,
                                            "autocolorscale": False
                                            },
                                        hovertext = df_merge['text'],
                                        hoverinfo = "text"
                                    )
                                ],
                                'layout' : go.Layout(
                                    width = 600,
                                    height = 270,
                                    template = "ggplot2",
                                    title = {
                                        'font': {'size':25},
                                        'y': 0.9,
                                        'x': 0.5,
                                        'xanchor': 'center',
                                        'yanchor': 'top'},
                                    margin = {'b': 1, 'l': 1, 'r': 1, 't': 1},
                                    geo = dict(
                                        resolution = 50,
                                        landcolor = 'rgb(204, 204, 204)',
                                        coastlinewidth = 1,
                                        lataxis = dict(range = [28, 47]),
                                        lonaxis = dict(range = [125, 150]),
                                    )     
                                )
                            }
                        ),
                    width = 7,
                    style = {"height": "100%",},
                ),
                dbc.Col(
                    dcc.Graph(
                        id = 'Number of infected people by prefecture',
                        figure = {
                            'data' : [
                                go.Bar(
                                    name='Cumulative number up to the previous day',
                                    x=df_count_by_date.index,
                                    y=df_count_by_date['gap'],
                                    ),
                                go.Bar(
                                    name='New number',
                                    x=df_count_by_date.index,
                                    y=df_count_by_date['China']
                                    )               
                            ],
                            'layout' : go.Layout(
                                width = 450,
                                height = 270,
                                legend = {
                                    'x': 0.05, 
                                    'y': 0.9,
                                    'bordercolor': 'black',
                                    'borderwidth': 1
                                    },
                                barmode = 'stack',
                                template = "ggplot2",
                                margin = {'b': 5, 'l': 5, 'r': 5, 't': 5},
                                xaxis_title = None,
                                yaxis_title = "Number of infected people"
                            )
                        }
                    ),
                    width = 5,
                    style = {"height": "100%"},
                ),
            ],
            className = "h-50",
        ),
    ],
    style = {"height": "90vh"},
)

if __name__ == "__main__":
    app.run_server(debug=True)

For the time being, I was able to insert the graph as I drew it. The graph also moves interactively and is interesting. However, the appearance is still unfinished, so we will improve the visuals from the next time onwards.

Recommended Posts

Create a layout by combining Dash and Bootstrap
Create a new list by combining duplicate elements in the list
I made a simple network camera by combining ESP32-CAM and RTSP.
Create a web map using Python and GDAL
Create a Mac app using py2app and Python3! !!
[Ubuntu] Install Android Studio and create a shortcut
How to create a Python 3.6.0 environment by putting pyenv on Amazon Linux and Ubuntu
Create a native GUI app with Py2app and Tkinter
Create a batch of images and inflate with ImageDataGenerator
Create a 3D model viewer with PyQt5 and PyQtGraph
Create a decent shell and python environment on Windows
Create a dictionary by searching the table using sqlalchemy
[Linux] Create a self-signed certificate with Docker and apache
I want to create a karaoke sound source by separating instruments and vocals using Python