rhondamuse.com

Creating an Interactive Sales Dashboard Using Streamlit and CSS

Written on

Chapter 1: Introduction to Data Visualization

In today's data-centric environment, visualizing information is not merely a requirement; it’s an art form. Striking a balance between practicality and visual appeal is essential to ensure that insights are represented accurately and captivate the audience. This tutorial provides a detailed guide on constructing a dynamic sales dashboard using Streamlit, incorporating custom CSS for a refined appearance, and utilizing synthetic data for demonstration purposes. It’s designed for data scientists, web developers, and anyone interested in data visualization.

Section 1.1: Getting Started with Streamlit

Streamlit is a powerful open-source framework that revolutionizes how data scientists and developers create interactive web applications. With the ability to convert data scripts into shareable web apps with minimal code, it streamlines the application development process. To begin using Streamlit, ensure Python is installed on your machine, and install Streamlit via pip:

pip install streamlit

Once installed, you can launch your web app with a straightforward Python script. Streamlit provides a variety of widgets and functionalities, allowing for the development of interactive features without needing a backend setup.

Section 1.2: Building the Sales Dashboard

Loading and Preparing Data

The first step involves data handling. Our script employs the read_ods function to import sales data from an ODS file using pandas for data manipulation. This function preprocesses the data by converting dates, sorting them, and extracting relevant details like product and category from the 'Order' column. This initial phase is vital for ensuring our visualizations are based on clean and organized data.

# Data loading and preprocessing

def read_ods(filename):

df = pd.read_excel(filename, engine='odf')

df['Date ordered'] = pd.to_datetime(df['Date ordered'])

df.sort_values('Date ordered', inplace=True)

df['Year'] = df['Date ordered'].dt.year

df['Month'] = df['Date ordered'].dt.strftime('%B')

df['Country'] = df['Delivery address'].apply(lambda x: x.split(',')[-1].strip())

numeric_cols = ['Revenue', 'Expenses', 'Profit']

df[numeric_cols] = df[numeric_cols].apply(pd.to_numeric, errors='coerce')

df['Product'] = df['Order'].apply(extract_product)

df['Category'] = df['Order'].apply(extract_category)

return df

Visualizing Data

Visual analytics are essential in our dashboard. We leverage Plotly to create interactive charts, such as revenue bar graphs and cumulative line charts. These visualizations offer a dynamic perspective on sales performance over time, enabling users to focus on specific periods for deeper analysis.

# Function to create a revenue bar graph

def create_revenue_bar_graph(df, selected_year, selected_month):

# Logic for filtering and creating the bar graph

pass

Displaying key metrics like total revenue, expenses, profit, and order count allows stakeholders to quickly assess the financial health of the business.

Mapping Orders by Country

Understanding the geographical distribution of sales can reveal trends and opportunities. Our dashboard includes a map visualization using Plotly Express to illustrate orders by country, providing insights into market reach and demand hotspots.

# Function to create a map of orders by country

def create_country_orders_map(df, selected_year):

# Logic for creating the country orders map

pass

Chapter 2: Enhancing the Dashboard

This video tutorial guides you through building a complete dashboard web app using Python and Streamlit. It covers essential concepts and practical tips for successful implementation.

In this video, learn how to create an Adidas sales dashboard with Streamlit and Plotly, focusing on data visualization techniques for effective analysis.

Customizing with CSS

While Streamlit provides a solid foundation for aesthetics, incorporating custom CSS allows for a tailored appearance that aligns with specific branding or stylistic needs. You can inject custom CSS into your Python script to modify text colors, backgrounds, and more.

def add_custom_css():

custom_css = """

.blue-header {

color: blue;

font-weight: bold;

}

"""

st.markdown(custom_css, unsafe_allow_html=True)

Creating synthetic sales data is invaluable for testing or demonstration purposes, especially when real data is unavailable. This capability enhances your ability to showcase the dashboard's features effectively.

Generating Synthetic Sales Data

The following script generates a dataset that simulates real sales transactions, complete with dates, revenue, expenses, and profit figures, providing a rich dataset for our dashboard.

import numpy as np

import pandas as pd

from datetime import datetime, timedelta

# Random seed and sample size

np.random.seed(42)

num_samples = 800 * 4

# Generate data

# Logic for generating synthetic data

pass

Finally, running your Streamlit application is simple. Open your terminal, navigate to the folder with your dashboard.py, and execute:

streamlit run dashboard.py

This command will launch your dashboard in your default web browser, making it easy to view and interact with your data insights.

By mastering these techniques, you position yourself to explore the expansive field of data visualization further, equipped to analyze sales, predict trends, and uncover valuable insights.

Happy coding and may your data stories shine!

Share the page:

Twitter Facebook Reddit LinkIn

-----------------------

Recent Post:

Omicron Unleashed: The New Villain in the COVID Saga

Omicron emerges as a comedic villain in the COVID narrative, expressing its disdain for normalcy and vaccinations while reveling in chaos.

Essential Life Lessons We Often Learn Too Late

Discover vital lessons about life that often come too late, encouraging personal growth and deeper understanding.

From Mediocrity to Mastery: Embracing Challenges for Success

Explore how embracing challenges leads to mastery and success.