Build Your own Data Dashboard
By: Vincent Tatan
Tags: Web Development, Business, Data Analysis, Data Science, Data Visualization

Definitive Guide for Data Professionals (Business Intelligence)

Build Your own Data Dashboard

Building dashboard web app quickly with Python Dash

Source: Unsplash

The Problem

The emergence of BI Dashboarding Tools. source: ezDataMunch

For data scientists, it is very important to communicate our data and results to the non technical users. Especially in the format which could be understood and reacted quickly. This is why data visualization is very important especially in BI products such as Power BI, Tableau and Qlikview.

Although they have an easy to use interface to produce stunning visualization, the technical licenses for these could be very costly. For Tableau, it could reach up to $50 per month. Furthermore for data professionals like me, I think that most BI Tools are not versatile enough to keep up with the dynamic growth of Python use cases. It still remains very clunky to embed this rather than seamlessly integrating with our web application.

Therefore, we need a better solution to this question.

Can we build an dashboard Web Application with Python for free?

The surprising answer is YES! I am going to exactly show you just that with the open source library — Dash Python.

Meet Dash!

Simply put, Dash is an open source Python Library to build web applications which are optimized for data visualization. The best thing about Dash is that it is built on top of Data visualization library such as Plotly and Matplotlib, Web Application Library (Flask), and finally data portable through Pandas! As the Javascript layer is handled via Plotly and Flask, you do not even need to touch other programming language to create a stunning web application.

The end result is the beautiful marriage of familiarity, conventions, and practicality. You could pick it up, develop, and deploy the application quickly. All of these are strictly writing only in Python and no other languages are necessary (although options are still available).

The power of Dash

One of the best features is that Dash supports declarative programming. This allows you to build Dash applications based on the input data and output properties. You will only state what you need and not the details on how to achieve your goal.

Source: Unsplash

Let us say you want to buy eggs.

Declarative Programming will say “ Find and buy eggs for me. Here are the cash”

However, Traditional Programming will say “ Go to the Courts Supermarket, go to the aisle 6 to find the eggs at your right hand corner, go to the cashier and pay with $5 cash”.

Obviously from this example declarative programming will offload the “how”. Similarly with money and eggs, you only need to hand over the input data and output properties then the visualization results will render automatically.

You do not even need to understand how Dash process your visualization. You will just instruct and receive the results. That is the beauty of Dash to support declarative programming.

In fact, this is not foreign at all. Many languages are also built with the same concepts. One example of the declarative language is SQL (Structured Query Language) and Kubernetes yaml. Both are important tools for Data Scientists to optimize their data retrieval and devops process.

Hope I make you excited!! Let’s get started

Dash in Action

Our Application in Big Picture, today we are going to learn how to build Dashboard with Dash

In this tutorial, you will learn how to build Dashboard Application with Dash Python.

We will visit our previous projects on task scheduler to web scrape data from Lazada (eCommerce) website and dump it into SQLite RDBMS Database. Then we will generate data visualizations to learn about price changes in Lazada Products over date and time.

Feel free to just enjoy this article or visit my Github Repo for the complete codes.

In this scenario let us visualize the change of price over the period of 3 days.

Price Optimization Dashboard Scraped from Lazada over 3 days

Let’s finish these 5 important steps to generate your first dashboard!

Importing and Activating Dash Preparing the data Visualizing Charts Dropdowns and Input Filter Selections Styling and Finishing

Importing and Activating Dash

As usual, let us import Dash Libraries on Python.

import dash

from dash.dependencies import Input, Output

import dash_core_components as dcc

import dash_html_components as html

you can download these libraries with a simple pip install command.

pip install <library name e.g: dash>

We will also activate the Dash Server with this code.

app = dash.Dash(__name__)

server = app.server

if __name__ == '__main__':

app.run_server(debug=True)

Once you run this Python script, it will run a server which you can open with http://127.0.0.1:8050/. This will open a flask web application which you could deploy anywhere such as Heroku. Notice that we put the run_server parameter debug =True. This will allow you to automatically update your local deployment once you save any changes in the scripts. Very neat time saving tricks to relaunch your application.

Info logs to run dash app on Command Prompt

Preparing the data

In this sector, we are going to read our product information from our database and dump them into a Pandas Dataframe. The dbm is a module that we created in SQLite RDBMS project before. This will dump a SQLite table into Pandas Dataframe which is called product_df . Feel free to extract the module from my Github.

global product_df

product_df = dbm.read()

The keyword global will globalize the product_df so that it is accessible to all call-back functions to generate data visualizations.

Visualizing Charts

Dash Graph with Component Details

We will create an app layout which will encapsulate html objects in the html module. This will be our main access to layout the graphs and and adjust the relative sizes to your view screen sizes.

app.layout = html.Div([

html.Div([

html.H1('Price Optimization Dashboard'),

html.H2('Choose a product name'),

dcc.Dropdown(

id='product-dropdown',

options=dict_products,

multi=True,

value = ["Ben & Jerry's Wake and No Bake Cookie Dough Core Ice Cream","Brewdog Punk IPA"]

),

dcc.Graph(

id='product-like-bar'

)

], style={'width': '40%', 'display': 'inline-block'}),

html.Div([

html.H2('All product info'),

html.Table(id='my-table'),

html.P(''),

], style={'width': '55%', 'float': 'right', 'display': 'inline-block'}),

html.Div([

html.H2('price graph'),

dcc.Graph(id='product-trend-graph'),

html.P('')

], style={'width': '100%', 'display': 'inline-block'})



])

Notice the dcc module. This is the dash core components which will store basic visualizations for web application such as barchart, dropdown, and line chart.

The rest is straightforward and specific to html module. You can create H1 or H2 headers, div (boxes to contain your web component), and even table. Think about it as the html codes abstracted so you do not need to even look at it.

Now let us talk about id . What does the id my-table in dcc.Graph(id=’my-table’) exactly mean? This shows the which function to call for a certain graph output. By inserting the code, we will call the function below.

@app.callback(Output('my-table', 'children'), [Input('product-dropdown', 'value')])

def generate_table(selected_dropdown_value, max_rows=20):



product_df_filter = product_df[(product_df['product_title'].isin(selected_dropdown_value))] product_df_filter = product_df_filter.sort_values(['index','datetime'], ascending=True)



return [html.Tr([html.Th(col) for col in product_df_filter .columns])] + [html.Tr([

html.Td(product_df_filter.iloc[i][col]) for col in product_df_filter .columns

]) for i in range(min(len(product_df_filter ), max_rows))]

On the top of the function code, you will see @app.callback which will run the magic. This means that you are exporting the return function exactly into the my-table component. You can also specify the input which is the selection from the drop down. This will be used to filter the product_df.

Noted the filtered product_df will be used to populate the return statement where we design the table using html module.

The beauty of this is that if you change the dropdown input in the dashboard, the function will render the filtered product_df.

Exactly how you use Tableau, but free and more versatile (plug and play)!!

Source: Meme Crunch

Dropdowns and Input Filter Selections

Notice the @app.callback input? This is the time where you can specify your own filter to render your visualization component.

dcc.Dropdown(

id='product-dropdown',

options=dict_products,

multi=True,

value = ["Ben & Jerry's Wake and No Bake Cookie Dough Core Ice Cream","Brewdog Punk IPA"]

),

The id is the same with the input annotation in the callback functions. This designates the function to call.

The options will insert the key value pairs of all the available options. This could be stocks ticker such as {‘GOOG’:google,’MSFT’: microsoft} or anything. For our case we will insert the same key value pairs which are the product name.

The multi attribute will allow you to select more than 1 option, which is perfect for this case to do a side by side price comparison in one chart.

Finally the value attribute will store your dropdown values at the start of server run.

Dropdown values to affect Python Dash Elements

Styling and Finishing

Styling in Dash is easy. By default, Dash already has a preconfigured setting to access assets folder. This is where you could overwrite the css for styling and js for web behavior. You can insert the stylesheet.css to beautify your Dash Web Application. Specific room for improvements would be the margin among components and table borders.

Inserting assets folder with stylesheet.css for styling

End Results

Congratulations!! You have created your first interactive dashboard. If you did it properly, you would be able to receive this result. If not, feel free to refer back to my Github Codes or post your questions here.

Your First Python Price Optimization Dashboard!!!

Now set free and create your own Dash Dashboard!

More References

If you need more examples and better insights of what Dash can do. Feel free to visit the following links. I assure you these will boost your Dashboard Design Skills to solve real life business problems.

Finally…

Source: Unsplash

I really hope this has been a great read and a source of inspiration for you to develop and innovate.

Please Comment out below to suggest and feedback. Just like you, I am still learning how to become a better Data Scientist and Engineer. Please help me improve so that I could help you better in my subsequent article releases.

Thank you and Happy coding :)

About the Author

Vincent Tatan is a Data and Technology enthusiast with relevant working experiences from Visa Inc. and Lazada to implement microservice architectures, business intelligence, and analytics pipeline projects.

Vincent is a native Indonesian with a record of accomplishments in problem solving with strengths in Full Stack Development, Data Analytics, and Strategic Planning.

He has been actively consulting SMU BI & Analytics Club, guiding aspiring data scientists and engineers from various backgrounds, and opening up his expertise for businesses to develop their products .

Please reach out to Vincent via LinkedIn , Medium or Youtube Channel