0% found this document useful (0 votes)
2 views9 pages

module_6

Module 6 focuses on developing and deploying interactive dashboards using Streamlit, emphasizing its integration with Python libraries for data analysis. It covers the structure, user controls, and advanced visualization techniques, including the use of Plotly and Matplotlib for enhanced interactivity and customization. The module also outlines deployment strategies to share dashboards effectively with stakeholders, ensuring usability and performance in real-world applications.

Uploaded by

mkuexams250
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views9 pages

module_6

Module 6 focuses on developing and deploying interactive dashboards using Streamlit, emphasizing its integration with Python libraries for data analysis. It covers the structure, user controls, and advanced visualization techniques, including the use of Plotly and Matplotlib for enhanced interactivity and customization. The module also outlines deployment strategies to share dashboards effectively with stakeholders, ensuring usability and performance in real-world applications.

Uploaded by

mkuexams250
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

LEARNING MODULE

Module 6 - Interactive Dashboard Development and Deployment


Instructional Hours: 4

1. Building interactive dashboards with Streamlit


Interactive dashboards play a central role in modern data analysis and decision-making. Un-
like static visualizations, interactive dashboards allow users to explore data dynamically, test
assumptions and derive insights tailored to their specific needs in real time.
Streamlit is a Python-based framework designed to simplify and accelerate the develop-
ment of interactive data applications. It enables analysts and researchers to transform Python
scripts into shareable web dashboards with minimal web-development knowledge. This lec-
ture introduces Streamlit as a practical tool for converting static Seaborn dashboards into
dynamic, interactive applications suitable for real-world use.

1.1. Why Streamlit for interactive ddashboards

Streamlit is particularly attractive as it aligns well with existing Python data science work-
flows. It integrates seamlessly with commonly used libraries such as Pandas, NumPy, Seaborn,
Matplotlib, and Plotly. Streamlit applications are written entirely in Python, require no sepa-
rate front-end code and update automatically as users interact with the dashboard.
Key advantages of Streamlit include:
• Rapid prototyping and development
• Minimal boilerplate code
• Built-in support for interactivity and layout
• Easy deployment and sharing

1.2. Dashboard structure and workflow

A Streamlit dashboard typically follows a structured workflow:


1. Import required libraries
2. Load and prepare data
3. Define the dashboard layout
4. Add user input controls
5. Generate visualizations that react to user inputs
Streamlit executes scripts from top to bottom each time a user interacts with the application.
Understanding this reactive execution model is essential for designing dashboards that are
both responsive and computationally efficient.

1.3. Adding user controls

User controls allow dashboard users to filter, customize and explore data without modifying
code. Streamlit provides a wide range of built-in widgets, including:
• Sliders: Useful for selecting numerical ranges such as years, income levels, or prices.

MASTER OF DATA SCIENCE Page 1 of 9


LEARNING MODULE

• Drop-down menus (select boxes): Enable users to choose categories such as regions, prod-
ucts, or demographic groups.
• Multi-select widgets: Allow selection of multiple categories simultaneously.
• Date selectors: Facilitate filtering of time-series data by specific dates or periods.
These widgets are commonly placed in the main dashboard area or in a sidebar and are linked
directly to variables used in data filtering and visualization logic.

1.4. Reactive updates and interactivity

A defining feature of Streamlit is its reactive behavior. Whenever a user changes an input
control, Streamlit automatically reruns the script and updates all dependent outputs. This
creates real-time interactivity without the need for explicit callback functions.
For example, selecting a different category from a drop-down menu can instantly update
charts, summary statistics and key performance indicators (KPIs). This reactive design sup-
ports exploratory data analysis and enables users to interactively test hypotheses and com-
pare scenarios.
To improve performance, especially when working with large datasets, developers can use
caching techniques to prevent unnecessary recomputation. Streamlit provides simple caching
mechanisms that allow frequently used data or calculations to be stored and reused efficiently.

1.5. Multi-page layouts and navigation

As dashboards increase in size and complexity, organizing content into multiple pages be-
comes essential. Streamlit supports multi-page applications that allow developers to sepa-
rate functionality into logical sections, such as:
• Overview and summary page
• Detailed analysis page
• Data description or methodology page
Multi-page layouts enhance usability and make dashboards easier to navigate, particularly
for non-technical users. Navigation menus allow users to move between pages seamlessly,
reflecting the structure of professional analytics platforms.

1.6. Integrating visualization libraries

Streamlit supports a variety of visualization libraries, making it both flexible and powerful. In
this topic, emphasis is placed on integrating:
• Seaborn: For statistical and aesthetically pleasing visualizations such as bar charts, box
plots, and heatmaps.
• Matplotlib: For highly customized charts requiring fine-grained control over visual elements.
• Plotly: For interactive visualizations that support hovering, zooming, and dynamic legends.
Existing Seaborn and Matplotlib visualizations can be reused within Streamlit with minimal
modification, allowing us to build directly on skills acquired in earlier coursework. Plotly visu-
alizations further enhance interactivity and user engagement.

MASTER OF DATA SCIENCE Page 2 of 9


LEARNING MODULE

1.7. From static to interactive dashboards

The practical objective of this topic is to convert a static Seaborn dashboard into a dynamic
Streamlit application. This process involves:
1. Identifying key parameters in the static dashboard, such as categories, time periods, or
variables of interest.
2. Replacing hard-coded values with Streamlit user input controls.
3. Linking user inputs to data filtering and transformation logic.
4. Ensuring that visualizations update automatically in response to user selections.
Effective dashboards require clear labeling, consistent design, minimal clutter, and concise
contextual explanations to enhance usability. Equal emphasis should be placed on clarity and
technical accuracy. Streamlit enables rapid creation of responsive, modular, and professional
dashboards, forming a strong foundation for advanced visualization methods and real-world
deployment.

2. Advanced visualization
Advanced visualization techniques enhance dashboards by enabling deeper data exploration,
comparison and interpretation. Beyond basic charts, effective dashboards combine interactiv-
ity, multiple visual forms, and careful customization to communicate complex patterns clearly.
Plotly and Matplotlib are complementary tools that allow analysts to design visually rich dash-
boards suitable for analytical, managerial, and policy-oriented contexts.

2.1. Interactive visualization with Plotly

Plotly is widely used for creating interactive, web-based visualizations. Its primary strength
lies in built-in interactivity, which enables users to engage directly with data through features
such as hover tooltips, zooming, panning, and legend-based filtering. Hover information al-
lows precise inspection of values without cluttering the chart, while zooming and panning
support detailed analysis of dense datasets.
Plotly also supports subplots, which allow multiple related charts to be displayed within a
single figure. Subplots are particularly useful for comparing trends across categories or vi-
sualizing multiple dimensions of the same dataset simultaneously. Presenting coordinated
views encourages analytical reasoning and supports richer interpretation.

2.2. Combining multiple chart types

Advanced dashboards typically integrate multiple chart types to provide a comprehensive


understanding of the data. For instance, line charts can illustrate trends over time, bar charts
can summarize categorical distributions, and scatter plots can reveal relationships between
variables. Combining these visual forms enables users to transition smoothly between high-
level summaries and detailed analysis.
To ensure interpretability, consistency in color schemes, axis scales, and labeling is essential.
Visual coherence across charts reduces cognitive load and strengthens comparative insights.

MASTER OF DATA SCIENCE Page 3 of 9


LEARNING MODULE

2.3. Advanced customization with Matplotlib

Matplotlib offers fine-grained control over visual elements, making it ideal for advanced cus-
tomization. Annotations can be used to highlight significant events, thresholds, or outliers di-
rectly on plots. Twin axes allow the display of two variables with different scales on the same
chart, facilitating comparison while conserving space. Inset charts provide focused views of
specific data regions, such as zoomed-in segments or supplementary distributions.
These techniques are especially valuable when producing publication-quality figures or tech-
nical visualizations that demand precision and clarity.

2.4. Handling large datasets in dashboards

Visualizing large datasets introduces performance challenges. Efficient strategies include fil-
tering data prior to visualization, aggregating observations, and limiting the number of plotted
points. Interactive tools such as Plotly enable dynamic filtering, allowing dashboards to re-
main responsive even when working with substantial datasets.
When we combine Plotly’s interactive capabilities with Matplotlib’s advanced customization
features, dashboards can achieve both analytical depth and visual sophistication. These tech-
niques support detailed exploration, meaningful comparison, and informed decision-making
in real-world applications.

3. Deploying and sharing dashboards


Deploying and sharing dashboards is a critical step in transforming analytical work into tools
that support real-world decision-making. While developing dashboards locally is useful for
testing and learning, deployment enables access by managers, policymakers, and other stake-
holders who may not have technical expertise. This section outlines the key steps involved in
deploying interactive dashboards:

Step 1: Preparing the dashboard for deployment

Before deployment, the dashboard code should be well-structured and tested. This includes:
• Organizing scripts clearly
• Removing unnecessary debugging outputs
• Ensuring all visualizations render correctly
Dependencies should be explicitly listed in a [Link] file to ensure consistent environ-
ments across development and production. Data paths should be handled carefully, avoiding
hard-coded local file references that may break when deployed.

Step 2: Selecting a hosting platform

The choice of hosting platform depends on the intended audience and scale of use:
• Streamlit cloud: Simple and cost-effective solution for hosting Streamlit apps directly from
version-controlled repositories.
• Dash enterprise: Suitable for organizations requiring advanced security, authentication, and
enterprise integration.

MASTER OF DATA SCIENCE Page 4 of 9


LEARNING MODULE

• Heroku: Flexible cloud hosting supporting multiple frameworks and greater control over
application configuration.
Understanding the strengths and limitations of each platform ensures an appropriate deploy-
ment strategy.

Step 3: Managing data sources

Deployed dashboards often rely on external data sources rather than static local files. Com-
mon sources include:
• CSV files stored in cloud repositories
• Relational databases
• APIs
Data access credentials should be managed securely, for example through environment vari-
ables rather than hard-coded values. Efficient data loading and caching strategies are essen-
tial to maintain responsiveness, particularly with large or frequently updated datasets.

Step 4: Sharing dashboards with stakeholders

Once deployed, dashboards can be shared via:


• Public URLs
• Restricted-access links
• Internal servers
Clear instructions should accompany shared dashboards, explaining their purpose, key fea-
tures, and limitations. Stakeholder-oriented sharing emphasizes usability and clarity, ensuring
non-technical users can interact with dashboards confidently and effectively.

Step 5: Ensuring responsiveness and scalability

A deployed dashboard must perform reliably under varying usage levels. Responsiveness
can be improved by optimizing visualizations, limiting unnecessary computations, and using
caching mechanisms. Scalability involves ensuring that the dashboard can accommodate in-
creased data volumes or additional users without performance degradation. Monitoring usage
and performance after deployment supports continuous improvement.

3.1. Summary

Effective deployment and sharing extend the value of dashboards beyond development envi-
ronments. By following structured deployment steps, managing data securely, and prioritizing
usability and performance, dashboards become practical tools for real-world analysis and in-
formed decision-making.

4. Practical example: Interactive dashboard


Creating interactive dashboards enables dynamic data exploration, real-time visualization,
and informed decision-making through user-driven controls and responsive charts

MASTER OF DATA SCIENCE Page 5 of 9


LEARNING MODULE

4.1. Interactive dashboard with iris dataset

The key steps include:

Step 1. Install Python

Ensure Python 3.8 or higher is installed:

python --version

Step 2. Create a virtual environment (Recommended)

# Create a new environment


python -m venv iris_dashboard_env

# Activate the environment


# Windows:
iris_dashboard_env\Scripts\activate

# Mac/Linux:
source iris_dashboard_env/bin/activate

Step 3. Install required packages

Inside the activated environment, install necessary packages:

pip install streamlit pandas plotly scikit-learn

Package explanations:
• streamlit: Framework to build interactive dashboards
• pandas: Data manipulation and handling
• plotly: Interactive charts
• scikit-learn: Provides the Iris dataset

Step 4. Source of data

The dashboard uses the Iris dataset from scikit-learn, which contains 150 samples of three
Iris species (setosa, versicolor, virginica) with 4 features: sepal length (cm), sepal width (cm),
petal length (cm) and petal width (cm). Data is loaded directly in Python:

from [Link] import load_iris

iris = load_iris(as_frame=True) # loads data as a pandas DataFrame


df = [Link]
df["species"] = df["target"].map(dict(enumerate(iris.target_names)))

No external CSV files are required.

MASTER OF DATA SCIENCE Page 6 of 9


LEARNING MODULE

Step 5. Save the dashboard code

• Copy your Streamlit dashboard code into a file named [Link].


• Ensure it includes the Iris dataset loading above.
• Save the file in a folder accessible from the terminal.

Step 6. Run the dashboard

Navigate to the folder containing [Link]:

cd path/to/your/folder

Run Streamlit:

streamlit run [Link]

• A browser window will open (usually at [Link]


• If not, copy the URL displayed in the terminal into a browser

Step 7. Using the dashboard

• Sidebar controls: Filter species and select X/Y axes for scatter plot
• Interactive scatter plot: Hover for exact values, zoom, and pan
• Distribution plot: Select feature to view overlaid histograms
• Data preview: Expand section to view filtered dataset

Step 8. Stop the dashboard

Press Ctrl + C in the terminal.

Step 9. Optional: Deploying online

The dashboard can be shared online using:


• Streamlit cloud: Direct deployment from GitHub
• PyCafe offers free hosting for Python web apps including Streamlit
• Hugging Face lets you host apps built with Streamlit (and Gradio) for free under their Spaces
platform.
• Check out other platforms even your personal websites or even in static Google sites
The Python code to assist with the above steps is provided below. You can modify as necessary
to suit your needs

4.2. Python code

# [Link]
import streamlit as st
import pandas as pd
import [Link] as px
from [Link] import load_iris

MASTER OF DATA SCIENCE Page 7 of 9


LEARNING MODULE

# Page configuration
st.set_page_config(
page_title="Iris Interactive Dashboard",
layout="wide"
)

[Link]("Interactive Iris Dashboard")


[Link]("Explore the Iris dataset using interactive controls and Plotly visualizations.")

# Load data
iris = load_iris(as_frame=True)
df = [Link]
df["species"] = df["target"].map(
dict(enumerate(iris.target_names))
)

# Sidebar controls
[Link]("Filter Options")

species_selected = [Link](
"Select species:",
options=df["species"].unique(),
default=df["species"].unique()
)

x_axis = [Link](
"Select X-axis variable:",
options=iris.feature_names,
index=0
)

y_axis = [Link](
"Select Y-axis variable:",
options=iris.feature_names,
index=1
)

# Filter data
filtered_df = df[df["species"].isin(species_selected)]

# Key metrics
col1, col2, col3 = [Link](3)

[Link]("Observations", len(filtered_df))

MASTER OF DATA SCIENCE Page 8 of 9


LEARNING MODULE

[Link]("Species Count", filtered_df["species"].nunique())


[Link]("Avg Sepal Length", round(filtered_df["sepal length (cm)"].mean(), 2))

# Interactive scatter plot


fig = [Link](
filtered_df,
x=x_axis,
y=y_axis,
color="species",
title=f"{y_axis} vs {x_axis}",
hover_data=iris.feature_names
)

st.plotly_chart(fig, use_container_width=True)

# Distribution plot
[Link]("Feature Distribution")

feature_selected = [Link](
"Select feature:",
iris.feature_names
)

hist_fig = [Link](
filtered_df,
x=feature_selected,
color="species",
barmode="overlay",
opacity=0.7
)

st.plotly_chart(hist_fig, use_container_width=True)

# Data preview
with [Link]("View Data"):
[Link](filtered_df)

MASTER OF DATA SCIENCE Page 9 of 9

You might also like