How to Create a Dashboard with Dash and Plotly(Part 2: Component and Style)

Dash

In the previous part, we discussed dashboard layout settings.

In this part, we will set up components such as drop-down list and set up styles such as fonts and margins.

The code presented in this article is available in the GitHub Repository here.

Dataset and Dashboard

In this case, we will use data from Kaggle’s tabular playground series Mar 2021. This data includes id, 19 categorical variables: cat0 – cat18, 11 continuous variables: cont0 – cont10, and a binary (0,1) target variable as shown in the table below.

The goal is to create the following dashboard with the sidebar section on the left and the content section on the right.

In the previous layout part, we have completed dividing the dashboard screen as shown in the figure below, so next we will set up components for the sidebar section.

Components Settings in Sidebar Section

The following 6 components are required for the sidebar section.

  • “Settings” in bold and in the size of Heading 5
  • Drop-down list for selecting the categorical variable
  • Drop-down list for selecting the continuous variable
  • Button for updating graphs
  • Horizontal line
  • Pie chart displaying the percentage of the target variable

Here we add five components to the code in the previous article, except for the last pie chart.

First, load the data. Next, create a list with categorical variable names and a list with continuous variable names for use as drop-down list choices.

import pandas as pd
import numpy as np


df = pd.read_csv('data/data_sample.csv')
vars_cat = [var for var in df.columns if var.startswith('cat')]
vars_cont = [var for var in df.columns if var.startswith('cont')]

Import dash_core_components as it is required to set up the dropdowns.

import dash_core_components as dcc

Next, change the sidebar variable to add a component as follows.

sidebar = html.Div(
    [
        dbc.Row(
            [
                html.H5('Settings',
                        style={'margin-top': '12px', 'margin-left': '24px'})
                ],
            style={"height": "5vh"},
            className='bg-primary text-white font-italic'
            ),
        dbc.Row(
            [
                html.Div([
                    html.P('Categorical Variable',
                           style={'margin-top': '8px', 'margin-bottom': '4px'},
                           className='font-weight-bold'),
                    dcc.Dropdown(id='my-cat-picker', multi=False, value='cat0',
                                 options=[{'label': x, 'value': x}
                                          for x in vars_cat],
                                 style={'width': '320px'}
                                 ),
                    html.P('Continuous Variable',
                           style={'margin-top': '16px', 'margin-bottom': '4px'},
                           className='font-weight-bold'),
                    dcc.Dropdown(id='my-cont-picker', multi=False, value='cont0',
                                 options=[{'label': x, 'value': x}
                                          for x in vars_cont],
                                 style={'width': '320px'}
                                 ),
                    html.P('Continuous Variables for Correlation Matrix',
                           style={'margin-top': '16px', 'margin-bottom': '4px'},
                           className='font-weight-bold'),
                    dcc.Dropdown(id='my-corr-picker', multi=True,
                                 value=vars_cont + ['target'],
                                 options=[{'label': x, 'value': x}
                                          for x in vars_cont + ['target']],
                                 style={'width': '320px'}
                                 ),
                    html.Button(id='my-button', n_clicks=0, children='apply',
                                style={'margin-top': '16px'},
                                className='bg-dark text-white'),
                    html.Hr()
                    ]
                    )
                ],
            style={'height': '50vh', 'margin': '8px'}),
        dbc.Row(
            [
                html.P('Target Variables', className='font-weight-bold')
                ],
            style={"height": "45vh", 'margin': '8px'}
            )
        ]
    )

The sidebar section is divided into three rows, with each dbc.Row as a single entity. In the first row, the string “Settings” is set to the size of Heading 5 in html.

The next row displays the following items in order.

  1. String “Categorical Variables”
  2. Drop-down list to select categorical variables
  3. String “Continuous Variables”
  4. Drop-down list to select continuous variables
  5. String “Continuous Variables for Correlation Matrix”
  6. Drop-down list for multiple selection of continuous variables
  7. Button to update graphs
  8. Horizontal line to make the border between the button and the string “Target Variables” clear

The strings (1st, 3rd, and 5th items) are displayed using html.P and the drop-down lists (2nd, 4th, and 6th items) are displayed using dcc.Dropdown. The dcc.Dropdown arguments are as follows

  • id: Any id can be given and used to identify the component in the callback settings.
  • multi: Multiple items can be selected if True.
  • value: Set initial values. Multiple items can be set to initial values by assigning a list.
  • options: Specify drop-down item list in dictionary format.

The button for updating the graphs (the 7th item) is displayed using html.Button. The arguments id and n_clicks are used to set up callbacks. The string to be displayed on the button is specified by children argument. Finally, html.Hr() is used to display a horizontal line.

Here, the last row is just “Target Varialbes” and the graph will be created later.

Running the script at this point will result in the figure below.

Next, set the style of each component, including width, font and color of text, etc.

Style Settings

Margin

Without margins, each component would be tightly packed around the edges of the screen, creating a cramped impression. First, create a margin at the top and left side of “Settings”. Margins are specified in dictionary form in the style argument. For the top margin, specify “margin-top”; for the left margin, “margin-left”, and the value can be specified in px. Set the style argument in html.H5 as follows to set the margins around “Settings” instead of the entire dbc.Row.

dbc.Row(
            [
                html.H5('Settings',
                        style={'margin-top': '12px', 'margin-left': '24px'})
                ],
            style={"height": "5vh"}
            )

Run it again and you can see that there are margins at the top and left of “Settings” as follows.

Font and Color Scheme

Dash allows the use of various bootstrap classes such as font, text color, background color, etc. by specifying the className. For more information on bootstrap classes, please see this cheat sheet. A portion of that cheat sheet is displayed in the table below.

Here we use the bootstrap class circled in red.

  • bg-primary: Background color is the primary color of the FLATLY theme set in the previous layout part, which is navy. For more information about FLATLY, click here.
  • text-white: Text color is white
  • font-italic:Text font is italic

To specify multiple bootstrap classes, write them in succession with a space between them as follows.

dbc.Row(
            [
                html.H5('Settings',
                        style={'margin-top': '12px', 'margin-left': '24px'})
                ],
            style={"height": "5vh"},
            className='bg-primary text-white font-italic',
            )

Run it again and you can see that the text is italic with white letters and the background color is navy.

Width of component

Adjust the width of the dropdown. Component width can be specified in px with the style argument. The following code is an example of the first drop-down.

dcc.Dropdown(id='my-cat-picker', multi=False, value='cat0',
                             options=[{'label': x, 'value': x}
                                      for x in vars_cat],
                             style={'width': '320px'}
                             )

Run it again and you can see that the width has been adjusted.

Dashboard after style settings

The code to apply the above knowledge to adjust the margins between components and set the font of strings is as follows. Margins and text fonts in the content section are also set to match the sidebar section.

import dash
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import numpy as np


df = pd.read_csv('data/data_sample.csv')
vars_cat = [var for var in df.columns if var.startswith('cat')]
vars_cont = [var for var in df.columns if var.startswith('cont')]

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

sidebar = html.Div(
    [
        dbc.Row(
            [
                html.H5('Settings',
                        style={'margin-top': '12px', 'margin-left': '24px'})
                ],
            style={"height": "5vh"},
            className='bg-primary text-white font-italic'
            ),
        dbc.Row(
            [
                html.Div([
                    html.P('Categorical Variable',
                           style={'margin-top': '8px', 'margin-bottom': '4px'},
                           className='font-weight-bold'),
                    dcc.Dropdown(id='my-cat-picker', multi=False, value='cat0',
                                 options=[{'label': x, 'value': x}
                                          for x in vars_cat],
                                 style={'width': '320px'}
                                 ),
                    html.P('Continuous Variable',
                           style={'margin-top': '16px', 'margin-bottom': '4px'},
                           className='font-weight-bold'),
                    dcc.Dropdown(id='my-cont-picker', multi=False, value='cont0',
                                 options=[{'label': x, 'value': x}
                                          for x in vars_cont],
                                 style={'width': '320px'}
                                 ),
                    html.P('Continuous Variables for Correlation Matrix',
                           style={'margin-top': '16px', 'margin-bottom': '4px'},
                           className='font-weight-bold'),
                    dcc.Dropdown(id='my-corr-picker', multi=True,
                                 value=vars_cont + ['target'],
                                 options=[{'label': x, 'value': x}
                                          for x in vars_cont + ['target']],
                                 style={'width': '320px'}
                                 ),
                    html.Button(id='my-button', n_clicks=0, children='apply',
                                style={'margin-top': '16px'},
                                className='bg-dark text-white'),
                    html.Hr()
                    ]
                    )
                ],
            style={'height': '50vh', 'margin': '8px'}),
        dbc.Row(
            [
                html.P('Target Variables', className='font-weight-bold')
                ],
            style={"height": "45vh", 'margin': '8px'}
            )
        ]
    )

content = html.Div(
    [
        dbc.Row(
            [
                dbc.Col(
                    [
                        html.P('Distribution of Categorical Variable',
                               className='font-weight-bold'),
                        ]),
                dbc.Col(
                    [
                        html.P('Distribution of Continuous Variable',
                               className='font-weight-bold')
                    ])
            ],
            style={'height': '50vh',
                   'margin-top': '16px', 'margin-left': '8px',
                   'margin-bottom': '8px', 'margin-right': '8px'}),
        dbc.Row(
            [
                dbc.Col(
                    [
                        html.P('Correlation Matrix Heatmap',
                               className='font-weight-bold')
                    ])
            ],
            style={'height': '50vh', 'margin': '8px'}
            )
        ]
    )

app.layout = dbc.Container(
    [
        dbc.Row(
            [
                dbc.Col(sidebar, width=3, className='bg-light'),
                dbc.Col(content, width=9)
                ]
            ),
        ],
    fluid=True
    )


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

Finally, run the script again.

Now we can set up the components and styles of our dashboard.

Going Further

In this part, we have discussed setting up components and styles. It is nearing completion. In the next part, we will create a graph using Plotly and set up callbacks to update the graph interactively.

コメント

タイトルとURLをコピーしました