Build a Stunning Sales Dashboard in Python Using Dash, Plotly & SQLite πŸ“Š

https://youtu.be/l1ldnBC8-as

Are you looking to turn raw sales data into actionable insights with interactive visualizations? In this blog post, you’ll learn how to create a modern, dynamic sales dashboard using Python, Dash, Plotly, and SQLite.

Whether you’re a data analyst, a sales manager, or a developer interested in business intelligence (BI), this tutorial is for you.

πŸ”§ Tools & Technologies Used

Before diving into the code, let’s review the stack:

  • SQLite – Lightweight database to store sales data.
  • Pandas – For querying and manipulating data.
  • Plotly Express – For rich, interactive charts.
  • Dash by Plotly – For building web-based Python dashboards.
  • Dash Bootstrap Components – To give the UI a professional look and feel.

πŸ“ Step 1: Prepare the Environment

Make sure you have the following packages installed:

pip install dash dash-bootstrap-components pandas plotly

Also, ensure your SQLite database (sales.db) contains a table called sales_data with columns: product, region, sales_amount, and sales_date.

🧠 Step 2: Read & Clean the Data

We start by connecting to the database and loading the data using pandas:

import sqlite3
import pandas as pd

conn = sqlite3.connect("sales.db")
query = """
SELECT
    product,
    region,
    sales_amount,
    sales_date
FROM    
    sales_data
"""
df = pd.read_sql(query, conn)
df['sales_date'] = pd.to_datetime(df['sales_date'])

πŸ–ΌοΈ Step 3: Build the Dashboard Layout

Using Dash and Bootstrap, we create a responsive layout with:

  • A dropdown to select a product.
  • Two graphs: a pie chart (sales by region) and a bar chart (monthly sales).
from dash import Dash, dcc, html
from dash.dependencies import Input, Output
import dash_bootstrap_components as dbc

app = Dash(__name__, external_stylesheets=[dbc.themes.CYBORG])
app.title = "Shiny Sales Dashboard"

app.layout = dbc.Container([
    html.H1("πŸ“ˆ Sales Dashboard", className="text-center my-4 text-primary"),

    dbc.Row([
        dbc.Col([
            html.Label("Select Product:", style={'font-weight': 'bold'}),
            dcc.Dropdown(
                options=[{'label': p, 'value': p} for p in df['product'].unique()],
                value=df['product'].unique()[0],
                id='product-dropdown',
                clearable=False
            )
        ], width=6),
    ]),

    dbc.Row([
        dbc.Col([dcc.Graph(id='sales-by-region')], width=6),
        dbc.Col([dcc.Graph(id='sales-over-time')], width=6),
    ])
], fluid=True)

πŸ”„ Step 4: Add Interactivity with Callbacks

This callback updates both charts whenever the user selects a different product:

import plotly.express as px

@app.callback(
    Output('sales-by-region', 'figure'),
    Output('sales-over-time', 'figure'),
    Input('product-dropdown', 'value')
)
def update_charts(selected_product):
    filtered_df = df[df['product'] == selected_product]

    # Pie Chart
    fig_region = px.pie(
        filtered_df,
        names='region',
        values='sales_amount',
        title=f"Sales by Region - {selected_product}",
        color_discrete_sequence=px.colors.sequential.RdBu
    )
    fig_region.update_traces(
        textinfo='percent+label',
        pull=[0.05] * len(filtered_df['region'].unique())
    )
    fig_region.update_layout(
        paper_bgcolor='rgba(0,0,0,0)',
        font_color='white'
    )

    # Monthly Sales Bar Chart
    monthly_df = filtered_df.copy()
    monthly_df['month'] = monthly_df['sales_date'].dt.to_period('M').astype(str)
    monthly_summary = monthly_df.groupby('month', as_index=False)['sales_amount'].sum()

    fig_time = px.bar(
        monthly_summary,
        x='month',
        y='sales_amount',
        title=f"Monthly Sales - {selected_product}",
        text_auto=True,
        color='sales_amount',
        color_continuous_scale="Plasma"
    )
    fig_time.update_layout(
        plot_bgcolor='rgba(0,0,0,0)',
        paper_bgcolor='rgba(0,0,0,0)',
        font_color="white",
        hovermode='x',
        xaxis_title="Month",
        yaxis_title="Total Sales"
    )

    return fig_region, fig_time

πŸš€ Step 5: Run the App

Finally, start the server:

app.run(debug=True)

Visit http://127.0.0.1:8050 in your browser to interact with your new dashboard.


🎯 Final Result

Your dashboard now:

  • Dynamically updates charts based on product selection.
  • Displays regional distribution of sales using a pie chart.
  • Tracks monthly trends in sales with a bar chart.
  • Has a dark mode theme thanks to Bootstrap CYBORG.

βœ… Conclusion

This project showcases how to combine SQL, Pandas, Dash, and Plotly into a beautiful, functional analytics dashboard. It’s easy to adapt this template to any kind of sales, marketing, or KPI reporting use case.

πŸ’‘ Pro Tips:

  • Add a date filter using dcc.DatePickerRange for more dynamic filtering.
  • Deploy your app with platforms like Heroku or Render for public access.
  • Export charts to PDF or PNG for stakeholder reports.

WHOLE FILE TO DOWNLOAD

Leave a Reply

Your email address will not be published. Required fields are marked *