Python For Data Science —Bootstrap For Plotly Dash Interactive Visualizations | by Nicholas Leong | Towards Data Science

Greetings data practitioners.
Welcome to 2021, where the new trend is all around Machine Learning.Most employers, even data scientists themselves, are drowning in the thought of deploying that new Machine Learning model that predicts literally everything for them.
If you have ever been in the field, you would understand that most organizations nowadays don’t have the sufficient fundamentals to even venture into Machine Learning, but they still want to.
They have not even scratched —
Proper data warehousing practices
Full understanding of data owned
Utilization of cloud tools to perform Machine Learning
That being said, data visualization will always stay a necessity in the data exploration stage. No one can properly understand data without some sort of help from visualizations. Thankfully, we have many libraries today that help us with that. Here are a few.
towardsdatascience.com
towardsdatascience.com
Hence, it is utterly important that you are able to communicate your findings through clean and beautiful visualizations as a data scientist. It will, without a doubt, make you stand out from the crowd.
Have you heard of Dash by Plotly?
Dash is the new kid on the block. I wrote about it here.
towardsdatascience.com
Dash is the new open-source Python library that enables you to build amazing data visualization apps without having to know any HTML, CSS, or Javascript.
Everything is in Python, giving Data Scientists who already know Python a really good time. Above all else, it’s fast, beautiful, and easy to learn.
Dash can also be programmed to update its dashboards in real-time, without any interactions.
It really is at the forefront of deploying and automating your dashboards, without the hassle of needing to manage deployment, mobile responsiveness, and the other stuff that comes along with SRE (Site Reliability Engineering).
So what are you waiting for, pick it up now!
In this article, we will go in-depth on how you can beautify your Dash Apps by implementing Bootstrap in Dash. It provides extremely useful tools like NavBars, Buttons, Forms, and many more.
But first, for those who don’t know — What exactly is a ‘Bootstrap’?
For those who have no knowledge of web-development — HTML and CSS make up the basic front-end skeleton of a webpage. I’m sure you’ve heard of them somewhere before.
Every website needs HTML and CSS, they’re like the fundamentals in building one.
Things get messy when it comes to optimizing websites for both desktop and mobile. According to Google, more than half of all web traffic comes from mobile. This situation has spawned an era where web developers start to put more priority on Mobile Sites and Apps.
This is where Bootstrap comes in.
Bootstrap is the most popular CSS framework right now in developing mobile responsive websites.
According to BuiltWith and w3tech, Bootstrap is ranked first in the CSS Framework space and makes up about 26.8% of all websites in the world which includes popular sites like Netflix and Udemy.
It makes front-end development faster and easier, saving you work during optimization for devices of all shapes.
One of the amazing features of bootstrap is the Grid system. By default, Bootstrap splits your layout into 12 columns that scale with whatever device you are using, making it a mobile responsive framework.
It also has predefined classes, which allows you to develop useful features like Buttons, NavBars, and Forms easily.
It will save you hours of work.
Now that’s out of the way, back to Dash.
Dash visualizations are based on Plotly.It would help a ton if you’re smooth with Plotly already.
To do that, you would also need solid fundamentals in data transformations using Pandas. I have written numerous guides on all the topics above, feel free to revise them before moving on.
towardsdatascience.com
You also understand basic Dash concepts like —
Dash’s layout is made up of core components and HTML components
Basic HTML concepts like Div and Container
Installation
pip install dashpip install dash-bootstrap-components
Working with Jupyter Notebooks
import dashimport dash_core_components as dccimport dash_html_components as htmlimport plotly.graph_objs as goimport pandas as pdimport dash_bootstrap_components as dbcfrom dash.dependencies import Input, Output
If you’re building a dashboard for whatever reason, it is important to design and organize it in a way that suits the user. Dash itself is not optimized for organizing purposes, we can use Bootstrap for that.
The Grid SystemWelcome to the Grid.
Bootstrap uses the Grid System to organize the elements on your website.In Bootstrap, your website is made up of rows and columns. You can split or group each row into different number of columns according to your needs.
What does it look like in pure HTML+ CSS:
<div class="container">  <div class="row">    <div class="col-sm">      One of three columns    </div>    <div class="col-sm">      One of three columns    </div>    <div class="col-sm">      One of three columns    </div>  </div></div>
What does it look like in Dash bootstrap:
row = html.Div(    [        dbc.Row(            [                dbc.Col(html.Div("One of three columns")),                dbc.Col(html.Div("One of three columns")),                dbc.Col(html.Div("One of three columns")),            ],no_gutters=True,        ),    ])
Both code blocks above produce the same thing, which is one row with default height that is split up into 3 columns, without any spacing in between the columns.
You can then add any of your elements like Dash Graphs, Dash buttons, and Navbars into these columns to properly organize them.
Important note to adjust heights and width — You can adjust the height of the row, and width of the columns
Let's try that.
app.layout = html.Div(    [        dbc.Row(dbc.Col(html.Div("A single, half-width column"), width=6,style={"border":"2px black solid"})),        dbc.Row(            dbc.Col(html.Div("An automatically sized column"), width="auto",style={"border":"2px black solid"})        ),        dbc.Row(            [                dbc.Col(html.Div("One of three columns"), width=3,style={"border":"2px black solid"}),                dbc.Col(html.Div("One of three columns"),style={"border":"2px black solid"}),                dbc.Col(html.Div("One of three columns"), width=3,style={"border":"2px black solid",'height':'10rem'}),            ]        ),],className = 'container')
By setting the width and height parameter in columns, we have complete control over how we want to organize our elements on the page.
By using dash bootstrap, you can also assign classes to all your components using the className parameter. Note how I assign the container class to the main Div here just by specifying it in the last line.
What are Classes?Classes are names you give to elements to assign certain design elements to them. You define these classes in a separate CSS file.
Let's say you create a class called ‘BIG’ and assigned the size = ‘2px’ to it.You can now assign this class to as many elements you want easily by stating className = ‘BIG’. It is a way more efficient and clean way in designing your elements.
With that, Let’s try it on actual visualizations.
app.layout = html.Div([                    dbc.Row([                        dbc.Col(scatterplot1, width=4),                        dbc.Col(scatterplot2, width=8),                    ])                ],className = 'container'            )
With the code block above, we have defined 2 scatterplots beforehand. The first scatterplot is set to be half the width of the second one.
This is extremely useful in planning and displaying your graphs properly. From my experience, if the user does not find it clean to look at, your charts/graphs will often go unnoticed.
People ignore designs that ignore people. — Frank Chimero, Designer
Now that we understand the basics, let’s move onto more fun stuff.How about setting up a totally functional navigation bar on your dashboard?
Let's set up a simple Navigation Bar that allows us to navigate to specific pages easily. The NavBar is responsive, stays on top of the page constantly, and is completely functional.
PLOTLY_LOGO = "https://images.plot.ly/logo/new-branding/plotly-logomark.png"# defining navbar itemshome_button = dbc.NavItem(dbc.NavLink('Home',href="#home", external_link=True,className='navlinks'))statistic_button = dbc.NavItem(dbc.NavLink('Statistics',href="#statistics", external_link=True,className='navlinks'))trend_button = dbc.NavItem(dbc.NavLink('Trend',href="#trend", external_link=True,className='navlinks'))news_button = dbc.NavItem(dbc.NavLink('News',href="#news", external_link=True,className='navlinks'))navbar = dbc.Navbar(    dbc.Container(    [        html.A(            dbc.Row(                [                    dbc.Col(html.Img(src=PLOTLY_LOGO,className = 'logo',height="30px")),                ],                align="center",                no_gutters=True,            ),            href="#home",        ),        dbc.NavbarToggler(id="navbar-toggler"),        dbc.Collapse(dbc.Nav([home_button,statistic_button,trend_button,news_button],className='ml-auto work-sans', navbar=True), id="navbar-collapse", navbar=True),    ],    ),    color="rgb(42,62,66)",    dark=True,    style = {'background-color':'#191919'},    className = 'navbar-change',    expand= 'lg')
First, we define all the buttons to place on the NavBar. These buttons are defined in NavLink while associating it with whatever page name we want it to bring us to. For example, the Statistics button has href = ‘#Statistics’ on it.We can then set the HTML.Header(id= ‘Statistics’) on the header of a page, clicking that button will bring us here.
You can clearly see that happening on the bottom left of the screen while we are clicking the buttons.
All the design is done through the color, style, and className parameters.All there’s left to do now is simply pass all the buttons as a list into the dbc.NavBar. Pretty straight forward.
You can read all about the dash bootstrap components here.
Jumbotrons are often used nowadays to bring your attention to featured content. You surely had to stumble upon it without even noticing. In this section, we will attempt to generate a Jumbotron using Dash Bootstrap.
Jumbotrons are perfect for landing pages.
The landing page is the page that the user lands on when they visit your dashboard/website. It is the first thing they see, so be sure to make a good impression.
Let’s try it out.
jumbotron = dbc.Jumbotron(    [        html.H1("Revenue Dashboard", className="display-3"),        html.P(            "A deep dive into revenue for the year, segmented by verticals.",            className="lead",        ),        html.Hr(className="my-2"),        html.P(            "Data is updated every day at 12pm."        ),        html.P(dbc.Button("Overview", color="primary"), className="lead"),    ])
A relatively simple landing Jumbotron consisting of a title, descriptions, and a button to bring the user to the main content of the page. Notice how we use className to design a lot of our elements here.
I’ve only used default class names here. You can find them from the official CSS class names here.
I hope this has shed light on how useful dash bootstrap can be. With this, you can completely design your dashboard with Python, while plotting your graphs with Pandas and Plotly.
Full code for the article:
Congratulations,you can now efficiently design your own dashboard completely in Python.
In this article, you have learned:
The Grid System
Organizing/Designing using Bootstrap
Navigation Bar
Jumbotron
Plenty for you to work on.Now go data practitioners, build something and share it with me,share it with the world.
If you hit a roadblock, feel free to reach out to me. You can find my information below.
We are not done yet with our data journey. I am working on more stories, writings, and guides on the data industry. You can absolutely expect more posts like this. In the meantime, feel free to check out my other articles to temporarily fill your hunger for data.
As usual, I end with a quote.
The goal is to turn data into information and information into insight. — Carly Fiorina
You can also support me by signing up for a medium membership through my link. You will be able to read an unlimited amount of stories from me and other incredible writers!
I am working on more stories, writings, and guides in the data industry. You can absolutely expect more posts like this. In the meantime, feel free to check out my other articles to temporarily fill your hunger for data.
Thanks for reading! If you want to get in touch with me, feel free to reach me at nickmydata@gmail.com or my LinkedIn Profile. You can also view the code for previous write-ups in my Github.