profile

Starting With Data

🟒 From Data to Decisions: The Step-By-Step Introduction to Crafting Executive Dashboards with Python & Plotly Dash (Code Included)

Published 5 months agoΒ β€’Β 5 min read

Business leaders are dumb.

That's what a lot of business analysts think because they create something "awesome" with a dataset and then it gets ignored.

Unfortunately, these types of business analysts don't realize that leaders aren't dumb. They are just busy. They are responsible for making decisions and making them quickly.

And leaders need answers (based on data) more than anything. Think about it: if they need answers and you have the skills to provide those answers...

You become their go-to data person.

The best way I've found to do that (based on my 15+ years of industry experience in solving real-world business problems with data) is to create dashboards that answer these questions.

And that's what you'll learn in today's in-depth tutorial.

By the way, if you haven't snagged your copy of The Data Analytics Portfolio Playbook, now's the time! Get up and running in two weeks or less. Data visualizations are awesome for your portfolio. The playbook includes everything you need to create an awesome portfolio -- including how to host for free.

Here's a specific example of what's possible when you follow the proven playbook.

Never send an Excel "report" again.

When you send a basic Excel report to a business leader, you send a signal:

  • You don't care about answering questions.
  • You think they should just be able to figure it out.
  • You only care about getting this to-do item off your list.
  • You can't be bothered wasting time providing more value.

Instead, you can build an awesome interactive dashboard for executives that answers questions (and answers them quickly) using Python and Dash.

Here's the step-by-step guide to take you through the entire process.

  • Step 1: Set Up Your Environment
  • Step 2: Prepare the Data
  • Step 3: Create the Dashboard Layout
  • Step 4: Add Callbacks for the Interactive Dropdown Filters
  • Step 5: Run the Dashboard and Share Your Insights

If you want to follow along with the code, here's the notebook.

And here's what you will build by the end of this tutorial:

Step 1: Set Up Your Environment

First, install and import the necessary Python packages:

!pip install dash
!pip install dash-bootstrap-components

from dash import Dash, html, dcc, Input, Output
import dash_bootstrap_components as dbc
import pandas as pd
import plotly.express as px

# Better image quality
%config InlineBackend.figure_formats = 'retina'

Step 2: Prepare the Data

Next, let's load up our data set and prepare the data for the dashboard:

For this tutorial, we're using the Superstore data set which shows fake sales data for a fake store. You should replace this with your own data set.

To prepare the data, we convert the Order Date column to a date object and also create a new Order Month column to summarize our data for a cleaner dashboard look.

Then, we use the groupby function to aggregate the data by Region and Order Month.

Our final data prep step is to create a Profit Ratio column based off monthly Profit and Sales.

Here's the code:

# Loading the dataset from a given URL into a pandas dataframe
url = 'https://raw.githubusercontent.com/PacktPublishing/Learning-Tableau-10/master/Chapter%2001/Superstore.csv'
df = pd.read_csv(url, encoding='unicode_escape')

# Convert 'Order Date' to datetime and extract month
df['Order Date'] = pd.to_datetime(df['Order Date'])
df['Order Month'] = df['Order Date'].dt.to_period('M').astype(str)


# Summarize data by Order Month
monthly_data = df.groupby(['Region', 'Order Month']).agg({
    'Sales': 'sum',
    'Profit': 'sum',
    'Order Quantity': 'sum'
}).reset_index()

monthly_data['Profit Ratio'] = monthly_data['Profit']/monthly_data['Sales']

# Quick check to see the summarized data
print(monthly_data.head())

Step 3: Create the Dashboard Layout

Then, let's create a 4-panel dashboard, with 2 charts on top and 2 on the bottom.

This is a great way to answer questions and solve business problems by piecing together a story.

Let's also add our dropdown in this step so that the end user can select any region:

# Define a modern color palette and font
colors = {
    'background': '#F5F5F5',
    'text': '#007BFF'
}
font_family = "Arial, Helvetica, sans-serif"

# Initialize the Dash app
app = Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])

# Define the app layout
app.layout = dbc.Container([
    dbc.Row(dbc.Col(dcc.Dropdown(
        id='region_dropdown',
        options=[{'label': i, 'value': i} for i in df['Region'].unique()],
        value='Central',
        multi=False
    ))),
    dbc.Row([
        dbc.Col(dcc.Graph(id='sales_graph'), md=6),
        dbc.Col(dcc.Graph(id='profit_graph'), md=6)
    ]),
    dbc.Row([
        dbc.Col(dcc.Graph(id='quantity_graph'), md=6),
        dbc.Col(dcc.Graph(id='profit_graph'), md=6)
    ])
], fluid=True)

# Define a function to apply styling to figures
def style_fig(fig):
    fig.update_layout(
        plot_bgcolor='#F5F5F5',
        paper_bgcolor='#F5F5F5',
        font=dict(
            family="Arial, Helvetica, sans-serif",
            color='#007BFF',
            size=12
        )
    )
    return fig

Step 4: Add Callbacks for the Interactive Dropdown Filters

To make the Region dropdown filter work, we need to add 'callbacks' into our code.

Let's also create a function to create the figures (graphs) as needed. This allows us to pass in a Region from the data set and get back out each of the figures we want to display in the dashboard.

Here's the code:

# Callback function for updating graphs
@app.callback(
    [Output('sales_graph', 'figure'),
     Output('profit_graph', 'figure'),
     Output('quantity_graph', 'figure'),
     Output('profit_ratio_graph', 'figure')],
    [Input('region_dropdown', 'value')]
)
def update_graphs(region):
    filtered_data = monthly_data[monthly_data["Region"] == region]

    # Create figures
    sales_fig = style_fig(px.bar(filtered_data, 
                                 x='order_month', y='Sales', 
                                 title='Monthly Sales'))
    profit_fig = style_fig(px.line(filtered_data, 
                                   x='order_month', y='Profit', 
                                   title='Monthly Profit'))
    quantity_fig = style_fig(px.bar(filtered_data, 
                                    x='order_month', y='Order Quantity', 
                                    title='Monthly Order Quantity'))
    profit_ratio_fig = style_fig(px.line(filtered_data, 
                                         x='order_month', y='Profit Ratio', 
                                         title='Monthly Profit Ratio'))

    return sales_fig, profit_fig, quantity_fig, profit_ratio_fig

Step 5: Run the Dashboard and Share Your Insights

Finally, we're ready to run the dashboard.

# Run the app
if __name__ == '__main__':
    app.run_server(debug=True)

Here's what it should look like!

If you followed along with the step-by-step tutorial, you're well on your way to mastering the fundamentals of data analytics with Python:

  • Building interactive dashboards from scratch using Python
  • Answer questions business leaders never thought to ask
  • Not letting your data skills become stale
  • Mastering a very in-demand skill

Never feel frustrated when communicating with data again.

The best way to avoid feeling insecure about communicating with business leaders with data is to build something that actually answers their questions.

And you have to do it quickly and effortlessly, which is where this tutorial helps.

Four things to keep in mind about building interactive dashboards with Python:

  1. ​This is just a starting point. Consider updating colors and fonts to match the style of your company.
  2. You can replace the SuperStore CSV data with your company's dataset and build the interaction you need to answer questions about your company.
  3. Business leaders aren't dumb. They are just busy! Don't make them think about what you are trying to tell them.
  4. Keep it simple. Don't try to jam too much data into one dashboard.​

Did this tutorial help? Hit reply and let me know or fill out this quick survey.

Until next time, keep exploring and happy blending!

Brian (say hi on X/Twitter!)

Whenever you're ready, here's how I can help you:

  1. Get more data analytics tips in my previous newsletter articles​
  2. Build your data analytics portfolio in 2 weeks with The Data Analytics Portfolio Playbook​

You are receiving this because you signed up for Starting with Data, purchased one of my data analytics products, or enrolled in one of my data analytics courses. Unsubscribe any time using the link below.

113 Cherry St #92768, Seattle, WA 98104
​Unsubscribe Β· Preferences​

Starting With Data

Weekly data analytics tutorials and guides. 5 minutes to read.

Learn to build analytics projects with SQL, Tableau, Excel, and Python. For data analysts looking to level up their career and complete beginners looking to get started. No fluff. No theory. Just step-by-step tutorials anyone can follow.

Read more from Starting With Data

Starting with Data Actionable data analytics tips, tricks, and tutorials to increase your earning potential. Delivered right to your inbox every Saturday. Python Data Blending Made Easy: 3 Simple Steps to Combine Data Sets in Python (Even if You’re Not Sure Where to Start) Hey Reader, Have you ever been given a few different spreadsheets and had to combine them into one? Use clunky VLOOKUPs in Excel Copy and paste (hoping you don't break something) Give up and ask a more technical coworker...

5 months agoΒ β€’Β 3 min read

Starting with Data Actionable data analytics tips, tricks, and tutorials to increase your earning potential. Delivered right to your inbox every Saturday. Stop Guessing, Start Visualizing: Turn Retail Data into Decision-Making Tools with Interactive Python Dashboards (Tutorial + Code) Hey Reader, You won't get noticed unless you are solving real-world business problems. find a problem create a solution share your work land your dream job Pretty simple. The hard part is knowing where to start....

5 months agoΒ β€’Β 5 min read

Starting with Data Actionable data analytics tips, tricks, and tutorials to increase your earning potential. Delivered right to your inbox every Saturday. Insights at a Glance: The Step-by-Step Process to Create an Interactive Hospitality Manager Dashboard using Python and Dash Data paralysis is a nightmare. It leads to only two outcomes: poor decision-making missed opportunities Instead, decision-makers need real insights at their fingertips. And you can help bring those insights to life by...

6 months agoΒ β€’Β 5 min read
Share this post