Skip to content
Topics
Streamlit
Build Interactive Data Dashboards with Streamlit: A Comprehensive Tutorial

Build Interactive Data Dashboards with Streamlit: A Comprehensive Tutorial

In the realm of data science, the ability to visualize and interact with your data is paramount. This is where Streamlit comes into play. Streamlit is an open-source Python library that allows you to create custom web apps for data exploration and visualization. In this tutorial, we will delve into the world of Streamlit and learn how to build interactive dashboards, deploy machine learning models, and more.

Have you heard of this awesome Data Analysis & Data Visualisation tool, that turns your Streamlit App into Tableau?

PyGWalker (opens in a new tab) is a Python Library that helps you easily embed a Tableau-like UI into your own Streamlit app effortlessly.

PyGWalker for Data visualization in Streamlit (opens in a new tab)

Introduction to Streamlit

What is Streamlit?

Streamlit is an open-source Python library that makes it easy to create custom web apps for machine learning and data science. In a world where data is king, Streamlit is the queen, providing the tools necessary to bring your data to life.

Streamlit's intuitive and user-friendly interface allows you to turn data scripts into shareable web apps quickly and easily. With just a few lines of code, you can create beautiful, interactive dashboards and data visualizations. Whether you're a seasoned data scientist or a beginner just dipping your toes into the data pool, Streamlit offers a versatile platform to help you understand and present your data.

The Benefits of Using Streamlit for Data Visualization

Data visualization is a critical aspect of data analysis. It allows us to understand complex data sets by representing them in a graphical, easy-to-understand format. Streamlit excels in this area, offering a range of benefits:

  • Real-time visualization: Streamlit's real-time capabilities mean that your dashboards will update instantly as your data changes. This is particularly useful for monitoring live data feeds or tracking KPIs.

  • Interactive dashboards: With Streamlit, your dashboards are not just static images, but interactive web apps. This allows users to manipulate the data, zoom in on specific areas, and really dive into the details.

  • Ease of use: Streamlit is designed to be user-friendly. You don't need to be a web developer to create stunning dashboards. If you can write Python code, you can use Streamlit.

  • Integration with Python data science stack: Streamlit integrates seamlessly with popular Python libraries like Pandas, NumPy, and Plotly, making it a powerful tool for any data scientist's arsenal.

Streamlit's Role in Machine Learning Models

Streamlit is not just for data visualization. It's also a powerful tool for machine learning. With Streamlit, you can quickly build interactive web apps to showcase your machine learning models. This can be particularly useful for demonstrating your model's capabilities to stakeholders or for debugging and model tuning.

For instance, you could build a Streamlit app that takes user input, passes it to your machine learning model, and displays the prediction in real-time. Or you could create an app that allows you to adjust the parameters of your model and see how it affects the output. The possibilities are endless.

Building a Dashboard with Streamlit

How to Build a Dashboard with Streamlit

Building a dashboard with Streamlit is a straightforward process. Here's a basic example to get you started:

import streamlit as st
import pandas as pd
 
# Load data
data = pd.read_csv('data.csv')
 
# Create a title
st.title('My First Streamlit Dashboard')
 
# Display data in a table
st.table(data)

In this example, we first import the necessary libraries. We then load our data using Pandas. Next, we create a title for our dashboard using the st.title() function. Finally, we display our data in a table using the st.table() function.

Real-time Data Dashboard with Streamlit

One of the key features of Streamlit is its ability to create real-time dashboards. This is particularly useful when working with live data feeds or when you need to monitor changes in your data over time.

To create a real-time dashboard, you can use Streamlit's st.write() function in a loop. Here's an example:

import streamlit as st
import pandas as pd
import time
 
# Create a title
st.title('Real-time Data Dashboard')
 
# Initialize an empty DataFrame
data = pd.DataFrame()
 
# Update data every second
for i in range(100):
    # Simulate new data
    new_data = pd.DataFrame({'value': [i]}, index=[time.time()])
    
    # Append new data to existing data
    data = data.append(new_data)
    
    # Display data
    st.write(data)
    
    # Wait 1 second before updating
    time.sleep(1)

In this example, we first create a title for our dashboard. We then initialize an empty DataFrame to store our data. Next, we enter a loop that simulates new data coming in every second. We append this new data to our existing data and display it using the st.write() function. Finally, we wait one second before updating the data again.

Interactive Data Visualization with Streamlit

Streamlit also allows you to create interactive data visualizations. This can be done using the st.plotly_chart() function, which integrates Streamlit with the Plotly library.

Here's an example of how you can create an interactive scatter plot:

import streamlit as st
import pandas as pd
import plotly.express as px
 
# Load data
data = pd.read_csv('data.csv')
 
# Create a scatter plot
fig = px.scatter(data, x='x', y='y')
 
# Display the plot
st.plotly_chart(fig)

In this example, we first load our data. We then create a scatter plot using Plotly Express. Finally, we display the plot using the st.plotly_chart() function.

This is just the tip of the iceberg when it comes to what you can do with Streamlit. With a bit of creativity and Python know-how, you can create stunning, interactive dashboards that bring your data to life.

Real-time Data Visualization with Streamlit

Streamlit's ability to handle real-time data is one of its most powerful features. This is particularly useful for applications that require constant monitoring or live updates. For instance, you could create a Streamlit dashboard to monitor IoT sensor data in real-time. Here's a simple example:

import streamlit as st
import random
import time
 
st.title('Real-time IoT Sensor Data')
 
data = []
 
for _ in range(100):
    data.append(random.randint(0, 100))
    st.line_chart(data)
    time.sleep(0.1)

In this example, we're simulating real-time IoT sensor data by generating random numbers and updating the line chart every 0.1 seconds.

Interactive Machine Learning Models with Streamlit

Streamlit's interactivity extends to machine learning models as well. You can create dashboards that allow users to tweak model parameters and see the effects in real-time. This can be a powerful tool for understanding how different parameters influence a model's predictions.

For example, let's say you have a machine learning model that predicts customer churn based on features like customer age, tenure, and monthly charges. You could create a Streamlit app that allows users to adjust these parameters and see the predicted churn probability in real-time. Here's a basic example:

import streamlit as st
from sklearn.ensemble import RandomForestClassifier
import numpy as np
 
st.title('Customer Churn Prediction')
 
# Load your trained model
model = RandomForestClassifier()
model.load('my_model.pkl')
 
# Get user input
age = st.slider('Age', 18, 100)
tenure = st.slider('Tenure (months)', 1, 72)
monthly_charges = st.slider('Monthly Charges', 20.0, 100.0)
 
# Make prediction
input_data = np.array([[age, tenure, monthly_charges]])
prediction = model.predict_proba(input_data)
 
# Display prediction
st.write(f'Churn Probability: {prediction[0][1]}')

In this example, we first load our trained model. We then use Streamlit's slider function to get user input for the age, tenure, and monthly charges. We pass this input to our model to make a prediction, and finally, we display the predicted churn probability.

IoT Data Visualization with Streamlit

With the rise of the Internet of Things (IoT), there's an increasing need for tools that can visualize IoT data. Streamlit is well-suited to this task, thanks to its real-time capabilities and ease of use.

For this example, let's assume we have a CSV file named sensor_data.csv that contains real-time IoT sensor data. Here's how you can display this data in Streamlit:

import streamlit as st
import pandas as pd
import time
 
st.title('Real-time IoT Sensor Data')
 
# Load the data
data = pd.read_csv('sensor_data.csv')
 
# Display the data in real-time
for i in range(len(data)):
    # Display the current data point
    st.line_chart(data[:i+1])
    
    # Wait for a short period of time before displaying the next data point
    time.sleep(0.1)

In this example, we first load the sensor data from the CSV file. We then display the data in real-time by gradually adding one data point at a time to the line chart. After each data point is added, we wait for a short period of time before adding the next one. This creates the effect of the data being displayed in real-time.

Conclusion

Streamlit is a powerful tool for creating interactive data dashboards. Whether you're visualizing real-time IoT data, showcasing a machine learning model, or just exploring a dataset, Streamlit offers a user-friendly and flexible platform to do so. With its Python-based syntax and wide range of features, it's no wonder that Streamlit is becoming a popular choice for data scientists and analysts alike. These examples only scratch the surface of what's possible with Streamlit, and I encourage you to explore its capabilities further.

Have you heard of this awesome Data Analysis & Data Visualisation tool, that turns your Streamlit App into Tableau?

PyGWalker (opens in a new tab) is a Python Library that helps you easily embed a Tableau-like UI into your own Streamlit app effortlessly.

PyGWalker for Data visualization in Streamlit (opens in a new tab)

Frequently Asked Questions

Is Streamlit good for dashboards?

Yes, Streamlit is an excellent tool for creating interactive data dashboards. It's Python-based, which makes it accessible to many data scientists, and it offers a wide range of features for data visualization and interactivity.

Is Streamlit better than Flask?

Streamlit and Flask serve different purposes. Flask is a general-purpose web framework, while Streamlit is specifically designed for creating data dashboards. If you're looking to build a data dashboard quickly and easily, Streamlit is likely the better choice.

What are the disadvantages of Streamlit?

While Streamlit is a powerful tool, it's not without its drawbacks. For one, it's not as customizable as some other dashboarding tools. Additionally, while it's great for creating simple, standalone apps, it might not be the best choice for more complex web applications.

Why is Dash better than Streamlit?

Whether Dash is better than Streamlit depends on your specific needs. Dash, which is also a Python library for creating interactive web applications, offers more customization options than Streamlit. However, Streamlit is often praised for its simplicity and ease of use, which can make it a better choice for quick prototyping and simple dashboards.