How to create dashboard in python

Learn to create interactive dashboards, manage data with pandas, and visualize insights using Plotly in simple steps.
Build AI Powered Interactive Dashboard with Databrain
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.

Making dashboards super simple with DataBrain

So far, you have created visualizations using Python and Dash. But the downside of this approach is you need programming knowledge or hire a developer.

With DataBrain, you can easily create various visualizations without knowing how to code. Here's how DataBrain helps:

  1. Create an account.
  2. Connect your database ( MongoDB, Snowflake, etc.)
  3. Drag and drop the data from your database to create a metric. Choose a visualization(pie, table, gauge, etc). Save it.
  1. Create as many metrics as you want and save all of them together as a dashboard. You can rearrange each metric or resize them as you see fit.

By following the above process, it becomes very easy to create dashboards within minutes.

You can easily share these dashboards or embed them in your websites or workflow. 

There are more features than we can discuss here, so book a free demo here and see it yourself.

Python Dashboards 101: Build Dashboards Using Python Easily

Dashboards are essential in data visualization because they simplify complex data into graphs and charts, helping users quickly grasp crucial information. 

While there are many ways to create dashboards, Python remains a popular choice for its versatility and power. Python has many libraries and frameworks that extend its use to web development and data analysis. Its flexibility makes it a top choice for creating dashboards and simplifying development.

Dash by Plotly is a Python library that makes building interactive dashboards easy. It combines Python and Plotly to create web applications with minimal effort. Dash includes various components, from HTML elements to advanced graphs and charts, helping developers create detailed and interactive dashboards. 

By simplifying web development, Dash lets developers focus on data insights, making it a valuable tool for anyone working with data.

Prerequisites:

Install the following on your computer before building a dashboard (ignore, if installed)

  1. Python
  2. VS Code

Setting up the environment:

Open the terminal in VS Code.

The following process is the same for Mac/Windows until step 3:

1. Create a new folder for your project: 

mkdir python_dashboard

2. Move into the new folder: 

cd python_dashboard

3. Create a virtual environment: 

python3 -m venv venv

4. Activate the virtual environment:

For Mac: source venv/bin/activate

For Windows: venv\Scripts\activate 

5. Now that your environment is ready, install the libraries you'll need for your dashboard: 

python3 -m pip install dash pandas

That's it! You have everything you need to start building your Python dashboard.

Data:

Python can read data from various sources such as CSV, Excel, HTML, JSON, SQL, XML, and Table.

We are taking sample CSV data for this tutorial to create a dashboard.

The sample data in the CSV format looks like this:

Building,Total Units,Occupied Units,Monthly Rent,Maintenance Cost,Occupancy Rate,Renewed Leases,Total Leases,Tenant Satisfaction Score
Building A,100,80,1200,200,0.8,70,100,4.0
Building B,150,120,1350,150,0.8,90,120,3.5
Building C,200,180,1100,250,0.9,150,170,4.2

Save this data as data.csv in the folder python_dashboard.

Note: Use actual data instead of the sample data when you create the dashboard. This data is for demonstration purposes only.

Create the charts:

Data Preprocessing: Before creating your dashboard, it's crucial to preprocess your data. This step ensures your visualizations are accurate and meaningful. Key preprocessing steps include:

  1. Handling missing values
  2. Removing duplicates
  3. Standardizing data formats
  4. Feature engineering (creating new columns based on existing data)
  5. Outlier detection and treatment

For this tutorial, we'll assume the data is clean, but in real-world scenarios, preprocessing is a critical step.

In this tutorial, we will build a property management dashboard using dash by Plotly.

First, create app.py in the folder python_dashboard and copy the below code.

Basic Dash app:

from dash import Dash, html - Importing dash and html from dash


from dash import Dash, html  # Importing dash and html from dash

app = Dash()  # Initializing the app

app.layout = [html.Div(children='Hello World')]  # This is where you write HTML and CSS

if __name__ == '__main__':  # These two lines are for running the app
    app.run(debug=True)

Run python3 app.py in the terminal and you will see “Hello World” in your browser at http://127.0.0.1:8050/

This is to check whether all the libraries and code is working perfectly. 

If it is working as expected,clear the previous code and proceed to building the dashboard. 

Import the following libraries in the app.py


import pandas as pd  # Importing pandas library
from dash import Dash, dcc, html  # Importing Dash components
import plotly.express as px  # Importing Plotly for visualizations

Here's a simpler way to understand the libraries:

  • pandas: You can use pandas to import data from files (like CSV), organize it into tables, and perform calculations.
  • Dash: Dash lets you create interactive web apps with layouts, buttons, dropdowns, and other elements.
  • plotly.express: Plotly.express helps you easily visualize your data from pandas in various ways like bar charts, scatter plots, and more.

In short:

  • pandas prepares your data
  • dash builds your interactive app
  • plotly.express visualizes your data within the app

CSS

For this tutorial, we are using Bulma css as follows. 

#Use Bulma for basic styling
app = Dash(external_stylesheets=[
          'https://cdn.jsdelivr.net/npm/bulma@0.9.3/css/bulma.min.css'])

Read CSV Data

# Read CSV data
df = pd.read_csv('data.csv')

We are going to create the following KPIs for the property management dashboard. 

  1. Occupancy rate
  2. Average monthly rent
  3. Maintenance cost per unit
  4. Vacancy rate
  5. Renewal rate
  6. Tenant satisfaction score

For this, we need to create the layout using app.layout.

Here is the code for occupancy rate:


html.Div(  # Occupancy Rate card
    className='column is-one-third',  # 1/3 width
    children=[
        html.P(
            children='Occupancy Rate (%)',
            className='has-text-centered mb-3'  # Smaller margin
        ),
        dcc.Graph(
            id='occupancy-rate-chart',
            figure=px.pie(df, values='Occupancy Rate',
                          names='Building', title=''),
            className='card'  # Style as a card for consistency
        ),
        html.Div(
            className='card-content',
            children=[
                html.P(
                    children=f"Average Occupancy: {df['Occupancy Rate'].mean():.2f}%",
                    className='has-text-centered'
                )
            ]
        )
    ]
),

Code breakdown:

Children 

In html.Div, children refers to the content placed inside the div container. In this case, it holds the title, graph, and average occupancy information.

Dcc.graph

id='occupancy-rate-chart' assigns a unique identifier to the graph for potential future use cases.

px.pie(...) from plotly.express creates a pie chart in this case.

  • Slice sizes show "Occupancy Rate" for each "Building".
  • Slice labels use "Building" names.

Average Occupancy:

  • Calculates the average occupancy rate from df.
  • Displays the average rate with two decimal places in a centered paragraph.

The code is similar for the other KPI as well. So, let’s look at the full code to understand it better. 

Read the comments to understand each part of the code clearly. 

import pandas as pd
from dash import Dash, dcc, html
import plotly.express as px


import pandas as pd
from dash import Dash, dcc, html
import plotly.express as px

# Use Bulma for basic styling
app = Dash(external_stylesheets=[
    'https://cdn.jsdelivr.net/npm/bulma@0.9.3/css/bulma.min.css'])

# Read CSV data
df = pd.read_csv('data.csv')

# Calculate occupancy rate
df['Occupancy Rate'] = (df['Occupied Units'] / df['Total Units']) * 100

# Calculate vacancy rate (Total Units - Occupied Units)
df['Vacancy Rate'] = 100 - df['Occupancy Rate']
df['Renewal Rate (%)'] = 100 * (df['Renewed Leases'] / df['Total Leases'])
df['Tenant Satisfaction Score'] = df['Tenant Satisfaction Score']

# Define app layout with responsive styling and Bulma classes
app.layout = html.Div(
    className='section',  # Bulma class for the main section
    children=[
        # Centered heading with spacing
        html.H1(children='Property Management KPIs',
                className='title has-text-centered mb-6'),
        html.Div(
            className='columns is-multiline',  # Bulma classes for multiline columns
            children=[
                html.Div(  # Occupancy Rate card
                    className='column is-one-third',  # 1/3 width
                    children=[
                        html.P(children='Occupancy Rate (%)',
                               className='has-text-centered mb-3'),  # Smaller margin
                        dcc.Graph(
                            id='occupancy-rate-chart',
                            figure=px.pie(df, values='Occupancy Rate',
                                          names='Building', title=''),
                            className='card'  # Style as a card for consistency
                        ),
                        html.Div(
                            className='card-content',
                            children=[
                                html.P(
                                    children=f"Average Occupancy: {df['Occupancy Rate'].mean():.2f}%",
                                    className='has-text-centered'
                                )
                            ]
                        )
                    ]
                ),
                html.Div(  # Average Monthly Rent card
                    className='column is-one-third',  # 1/3 width
                    children=[
                        html.P(children='Monthly Rent',
                               className='has-text-centered mb-3'),  # Smaller margin
                        dcc.Graph(
                            id='avg-rent-chart',
                            figure=px.line(df, x="Building",
                                          y="Monthly Rent", title=''),
                            className='card'  # Style as a card for consistency
                        ),
                        html.Div(
                            className='card-content',
                            children=[
                                html.P(
                                    children=f"Average Monthly Rent: ${df['Monthly Rent'].mean():.2f}",
                                    className='has-text-centered'
                                )
                            ]
                        )
                    ]
                ),
                html.Div(  # Maintenance Cost per Unit card
                    className='column is-one-third',  # 1/3 width
                    children=[
                        html.P(children='Maintenance Cost per Unit',
                               className='has-text-centered mb-3'),  # Smaller margin
                        dcc.Graph(
                            id='maintenance-cost-chart',
                            figure=px.scatter(
                                df, x="Building", y="Maintenance Cost", title=''),
                            className='card'  # Style as a card for consistency
                        ),
                        html.Div(
                            className='card-content',
                            children=[
                                html.P(
                                    children=f"Average Cost: ${df['Maintenance Cost'].mean():.2f}",
                                    className='has-text-centered'
                                )
                            ]
                        )
                    ]
                ),
                html.Div(  # Vacancy Rate card
                    className='column is-one-third',  # 1/3 width
                    children=[
                        html.P(children='Vacancy Rate (%)',
                               className='has-text-centered mb-3'),  # Smaller margin
                        dcc.Graph(
                            id='vacancy-rate-chart',
                            figure=px.bar(
                                df, x="Building", y="Vacancy Rate", title=''),
                            className='card'  # Style as a card for consistency
                        ),
                        html.Div(
                            className='card-content',
                            children=[
                                html.P(
                                    children=f"Average Vacancy Rate: {df['Vacancy Rate'].mean():.2f}%",
                                    className='has-text-centered'
                                )
                            ]
                        )
                    ]
                ),
                html.Div(  # Renewal Rate card
                    className='column is-one-third',  # 1/3 width
                    children=[
                        html.P(children='Renewal Rate (%)',
                               className='has-text-centered mb-3'),  # Smaller margin
                        dcc.Graph(
                            id='renewal-rate-chart',
                            figure=px.pie(df, values='Renewal Rate (%)',
                                          names='Building', title=''),
                            className='card'  # Style as a card for consistency
                        ),
                        html.Div(
                            className='card-content',
                            children=[
                                html.P(
                                    children=f"Average Renewal Rate: {df['Renewal Rate (%)'].mean():.2f}%",
                                    className='has-text-centered'
                                )
                            ]
                        )
                    ]
                ),
                html.Div(  # Tenant Satisfaction Score card
                    className='column is-one-third',  # 1/3 width
                    children=[
                        html.P(children='Tenant Satisfaction Score',
                               className='has-text-centered mb-3'),  # Smaller margin
                        dcc.Graph(
                            id='tenant-satisfaction-chart',
                            figure=px.bar(
                                df, x="Tenant Satisfaction Score", title=''),
                            className='card'  # Style as a chart for consistency
                        ),
                        html.Div(
                            className='card-content',
                            children=[
                                html.P(
                                    children=f"Average Satisfaction Score: {df['Tenant Satisfaction Score'].mean():.2f}",
                                    className='has-text-centered'
                                )
                            ]
                        )
                    ]
                )
            ]
        )
    ]
)

if __name__ == '__main__':
    app.run(debug=True)

Dashboards made easy with Python and Dash

You've built your first interactive dashboard with Python and Dash. Now, you can turn the data you care about into clear, visual insights.

This tutorial covered the basics:

  • Setting up your environment
  • Using pandas to manage your data
  • Creating charts with plotly.express

Dashboard Design Best Practices:

  1. Keep it simple and focused.
  2. Use appropriate chart types for your data.
  3. Maintain a consistent color scheme.
  4. Provide context with labels and titles.
  5. Arrange components logically.
  6. Use whitespace effectively.

Play around with different data and experiment with Dash's features to make your dashboards truly shine. More charts, layouts, and ways to interact with your data exist.

Advanced Dash Features: For those looking to expand their dashboard capabilities, explore these advanced Dash features:

  1. Callbacks for dynamic updates
  2. Custom CSS for unique styling
  3. Dash DataTable for interactive data tables
  4. Dash DAQ for instrument panels and gauges

Performance Optimization: When dealing with larger datasets, consider these optimization techniques:

  1. Use efficient data structures (e.g., pandas DataFrames).
  2. Implement data caching.
  3. Use server-side data processing.
  4. Optimize database queries.
  5. Consider using Dash's built-in performance profiler.

Keep it simple and focus on what information you want to convey. With Python and Dash on your side, you're on your way to becoming a data visualization pro. Happy dashboarding!

Related Read:

Make customer facing analytics your competitive advantage