Streamlit : 5 simple steps to create awesome data visualizations.
Data visualization is an essential part of data analysis, helping to make complex data more understandable and accessible. Whether you’re a data scientist, a developer, or a business analyst, visualizing your data effectively is crucial. Streamlit, an open-source Python library, makes it incredibly easy to build and deploy beautiful data visualization applications with just a few lines of code.
In this blog, we’ll cover how to make data visualization with Streamlit, from installation to building interactive and dynamic dashboards.
What is Streamlit?
Streamlit is an open-source Python framework that allows you to turn data scripts into shareable web apps quickly and easily. Streamlit’s intuitive API enables you to create interactive visualizations, dashboards, and machine learning applications without requiring extensive front-end or web development skills. You simply write Python code, and Streamlit handles the rest, providing a smooth and responsive web interface.
Why Use Streamlit for Data Visualization?
Streamlit is loved by the data science and Python community for several reasons:
- Easy to Use: Streamlit is incredibly simple to learn. You don’t need HTML, CSS, or JavaScript to create a fully interactive app.
- Fast Prototyping: Quickly build and test your data visualization apps with minimal setup.
- Interactive Widgets: Add sliders, buttons, and other UI elements with minimal effort.
- Integration with Data Libraries: Works seamlessly with popular Python data libraries such as Pandas, Matplotlib, Plotly, and Altair.
Installing Streamlit (Step-by-Step)
Let’s start by installing Streamlit on your machine. The process is straightforward and works for both beginners and experienced developers.
Step 1: Install Python and Pip
Streamlit requires Python 3.7+ to be installed on your system. If you don’t have Python installed, download it from the official Python website.
Once Python is installed, install pip (Python’s package installer) by running the following command:
pip install --upgrade pip
Step 2: Install Streamlit
Now, use pip to install Streamlit:
pip install streamlit
After the installation is complete, verify it by running:
streamlit --version
Step 3: Launch Streamlit
You can now create a simple Streamlit app by opening a terminal, creating a Python script, and running the following command:
streamlit hello
This will launch a sample Streamlit app in your default browser, showcasing some of the framework’s capabilities.
Making Data Visualization with Streamlit (Hands-On Example)
Now, let’s dive into building a basic data visualization app using Streamlit. For this example, we will visualize a dataset using Pandas and Matplotlib—two widely used Python libraries.
Step 1: Set Up Your Environment
First, create a new directory for your Streamlit project and navigate to it:
mkdir streamlit_data_viz
cd streamlit_data_viz
Inside the directory, create a Python script called app.py
.
Step 2: Import Required Libraries
In app.py
, import the necessary libraries for our project:
import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt
Step 3: Load Your Data
For this example, we will use a simple CSV file containing sales data. You can load your own dataset or use a sample dataset from Pandas.
# Load a sample dataset
@st.cache
def load_data():
data = pd.read_csv("sales_data.csv")
return data
data = load_data()
st.write("Sales Data", data)
Make sure you have the CSV file saved in your project folder, or use a dataset available online.
Step 4: Create Your Data Visualization
Now, let’s create a basic line chart to visualize sales trends using Matplotlib.
# Plot a line chart of sales data
st.title('Sales Trend Over Time')
fig, ax = plt.subplots()
ax.plot(data['Date'], data['Sales'], color='blue', marker='o')
ax.set_xlabel('Date')
ax.set_ylabel('Sales')
ax.set_title('Sales Over Time')
st.pyplot(fig)
This will display a basic line chart of sales data over time within the Streamlit app.
Step 5: Add Interactivity with Streamlit Widgets
Streamlit makes it easy to add interactive components such as sliders and filters. Let’s add a slider to filter data by a specific range of dates.
# Add a slider to filter data by date range
st.sidebar.title("Filter Options")
start_date, end_date = st.sidebar.select_slider(
"Select Date Range:",
options=data['Date'].unique(),
value=(data['Date'].min(), data['Date'].max())
)
filtered_data = data[(data['Date'] >= start_date) & (data['Date'] <= end_date)]
st.write(f"Filtered Sales Data from {start_date} to {end_date}", filtered_data)
# Update the chart with filtered data
fig, ax = plt.subplots()
ax.plot(filtered_data['Date'], filtered_data['Sales'], color='green', marker='o')
ax.set_xlabel('Date')
ax.set_ylabel('Sales')
ax.set_title(f'Sales Trend from {start_date} to {end_date}')
st.pyplot(fig)
Now, users can select a date range using the sidebar slider, and the data visualization will update automatically based on their selection.
Deploying Your Streamlit App on AWS
Once you’ve built your Streamlit app, you can deploy it on AWS using Elastic Beanstalk, EC2, or another service. Here’s a simple guide to deploying it on AWS EC2.
Step 1: Set Up EC2 Instance
- Log in to your AWS Management Console.
- Launch a new EC2 instance with Ubuntu as the operating system.
- After the instance is up and running, SSH into the instance.
Step 2: Install Python and Streamlit on EC2
Once inside your EC2 instance, install Python, pip, and Streamlit:
sudo apt update
sudo apt install python3-pip
pip3 install streamlit
Step 3: Transfer Your Project Files
Use SCP (Secure Copy Protocol) to transfer your Streamlit app files from your local machine to the EC2 instance:
scp -i your-aws-key.pem -r /path/to/streamlit_data_viz/ ubuntu@your-ec2-ip:/home/ubuntu/
Step 4: Run Your Streamlit App
Navigate to your project directory on EC2 and run your Streamlit app:
cd streamlit_data_viz
streamlit run app.py --server.enableCORS false --server.port 80
Your Streamlit app will now be accessible via the public IP address of your EC2 instance.
Conclusion
Streamlit is an excellent framework for building and sharing interactive data visualization apps with ease. From its straightforward installation process to creating dynamic visualizations, Streamlit enables anyone with basic Python knowledge to build powerful, web-based data tools. Whether you’re working with datasets, building ML apps, or automating workflows, Streamlit has you covered.
By following this guide, you’ve learned how to install Streamlit, create a simple data visualization app, add interactivity, and deploy it to AWS. Now, it’s your turn to explore the possibilities Streamlit offers and start visualizing your data in a new and engaging way.