Creating Interactive Dashboards with Streamlit and Python
Interactive dashboards are powerful tools for exploring, analyzing and communicating data insights. By visualizing key metrics and allowing users to slice and dice the data, interactive dashboards enable data-driven decision making and help uncover trends and patterns that may not be obvious from looking at raw data alone.
While building custom interactive dashboards has traditionally required knowledge of web development and frameworks like React, there are now easier solutions. Streamlit is an open-source Python library that lets you create web apps and interactive dashboards using simple Python scripts.
In this guide, we‘ll walk through step-by-step how to build an interactive dashboard using Streamlit and Python. Whether you‘re a data scientist, analyst or engineer, Streamlit makes it simple to turn your analyses into usable, shareable web apps. Let‘s get started!
What is Streamlit?
Streamlit is an open-source app framework built specifically for machine learning and data science projects. The key idea behind Streamlit is that you can create beautiful, interactive apps by writing simple Python scripts.
Streamlit takes care of all the web development pieces behind the scenes, so you can focus purely on your data and analysis. Some notable features of Streamlit include:
- Browser-based: Streamlit apps are pure Python scripts that run in a web browser, making them easily shareable
- Built-in components: Streamlit provides a variety of built-in UI components like sliders, dropdowns, tables and charts, making app development fast
- Interaction and live updates: Every time you update your Python script, the changes are reflected live in the app
- Integration with data science tools: Streamlit integrates seamlessly with data manipulation and visualization libraries like pandas, matplotlib, plotly, etc.
- Customizable theming: While Streamlit has a clean default style, you can easily customize the look and feel of your app with themes
- Deployable: Streamlit apps can be deployed in just a few clicks to Streamlit‘s sharing platform or your own hosting environment
In essence, Streamlit combines the simplicity of Python scripting with the interactivity and visual appeal of web apps. This makes it an excellent tool for data scientists and analysts to build interactive dashboards, machine learning demos, and data-driven web applications.
Building a Dashboard with Streamlit
Now that we have an overview of what Streamlit is and why it‘s useful, let‘s dive into actually creating an interactive dashboard. We‘ll build a dashboard to explore and analyze a dataset of Airbnb listings.
1. Installing and Importing Libraries
First, make sure you have Python 3.7+ and pip installed. Then install Streamlit using pip:
pip install streamlit
Next, create a new Python file (e.g. airbnb_dashboard.py) and import the necessary libraries:
import streamlit as st
import pandas as pd
import numpy as np
import plotly.express as px
We import streamlit for building the web app, pandas for data manipulation, numpy for numerical computing, and plotly.express for interactive visualizations.
2. Loading and Preparing Data
Download the Airbnb listings dataset (e.g. from Kaggle) and read it into a pandas DataFrame:
df = pd.read_csv("listings.csv")
Perform any necessary data cleaning and preparation, such as handling missing values, converting data types, and deriving new features. For example:
df["price"] = df["price"].str.replace("$","").str.replace(",","").astype(float)
df["reviews_per_month"] = df["reviews_per_month"].fillna(0)
df["host_acceptance_rate"] = df["host_acceptance_rate"].str.rstrip("%").astype(float)
3. Creating Visualizations
The core of our dashboard will be data visualizations that allow exploration of the Airbnb listings. Streamlit supports several charting libraries, but we‘ll use plotly for its interactivity and aesthetic appeal.
Let‘s start with a simple histogram of the listing prices:
st.header("Price Distribution")
fig = px.histogram(df, x="price", nbins=30)
st.plotly_chart(fig)
The st.header displays text in header formatting, while st.plotly_chart renders the plotly figure.
We can add more charts to visualize other aspects of the data:
st.header("Listings by Neighborhood")
neighborhood_counts = df["neighbourhood"].value_counts()
fig = px.bar(neighborhood_counts, x=neighborhood_counts.index, y=neighborhood_counts.values)
st.plotly_chart(fig)
st.header("Review Scores")
review_cols = ["review_scores_accuracy", "review_scores_cleanliness", "review_scores_checkin",
"review_scores_communication", "review_scores_location", "review_scores_value"]
fig = px.box(df, y=review_cols)
st.plotly_chart(fig)
4. Laying Out the Dashboard
Streamlit provides several options for organizing content on the page. The simplest is to just stack elements vertically, which is what we‘ve done so far.
For a more organized layout, we can use columns:
col1, col2 = st.columns(2)
with col1:
st.header("Expensive Listings")
expensive = df.nlargest(10, "price")
st.dataframe(expensive[["name", "neighbourhood", "room_type", "price"]])
with col2:
st.header("Bargain Listings")
cheapest = df.nsmallest(10, "price")
st.dataframe(cheapest[["name", "neighbourhood", "room_type", "price"]])
The st.columns function creates a grid of columns, and the with syntax lets us place content in each column.
We can also use expanders and containers to group related content and optimize use of space:
with st.expander("Data Description"):
st.write(df.describe())
with st.container():
st.subheader("Correlations")
corr = df.corr()
fig = px.imshow(corr, text_auto=True)
st.plotly_chart(fig)
Expanders create collapsible sections, while containers let you treat multiple elements as a single unit for layout purposes.
5. Adding Interactivity
To make our dashboard interactive, we can use Streamlit‘s input widgets. These allow the user to modify parameters using UI controls, triggering updates in the app.
For instance, let‘s add a price range slider to filter the listings:
price_min, price_max = st.slider("Price Range", float(df["price"].min()), float(df["price"].max()),
(50., 500.))
filtered_df = df[(df["price"] >= price_min) & (df["price"] <= price_max)]
st.write(f"Showing {len(filtered_df)} listings with prices between ${price_min} and ${price_max}")
st.map(filtered_df[["latitude", "longitude"]])
The st.slider function creates a slider widget, which we use to filter the DataFrame. The filtered results are shown on a map using st.map.
Similarly, we can add a multi-select dropdown to filter listings by amenities:
all_amenities = set(df["amenities"].str.split(",").explode())
selected_amenities = st.multiselect("Amenities", all_amenities)
mask = df["amenities"].str.split(",").apply(lambda x: set(selected_amenities).issubset(x))
amenities_df = df[mask]
st.write(amenities_df)
The st.multiselect creates a dropdown menu that allows selecting multiple values. We use the selected amenities to filter the DataFrame to only listings containing all of the selected amenities.
With widgets like sliders, dropdowns, radio buttons and text inputs, you can add all sorts of interactivity to your Streamlit dashboard, empowering users to engage with the data.
6. Styling the Dashboard
While Streamlit has an attractive default theme, you may want to customize your dashboard‘s appearance. Streamlit provides a few options for visual tweaks.
To set a custom page title and favicon:
st.set_page_config(page_title="Airbnb Dashboard", page_icon=":house:", layout="wide")
To change the default fonts and colors, create a custom CSS file and point Streamlit to it:
st.markdown("""
<style>
@import url(‘https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap‘);
body {
font-family: ‘Roboto‘, sans-serif;
color: #262730;
}
</style>
""", unsafe_allow_html=True)
Here we import the Roboto Google Font and apply it to the body text. We can target specific Streamlit elements by their CSS selectors to further customize the look.
7. Deploying the Dashboard
Once your dashboard is ready, it‘s time to share it with the world! The easiest way is to use Streamlit‘s own sharing platform:
- Put your dashboard script on GitHub
- Sign into share.streamlit.io and click "New app"
- Select your GitHub repo, branch and file
- Click "Deploy"
Streamlit will bundle your app and dependencies, and provide a public URL you can share. The app will automatically update whenever you push changes to GitHub.
Alternatively, you can deploy Streamlit apps to other hosting services like Heroku or AWS, or serve them locally for internal organizational use.
Advanced Streamlit Features
As you build more complex dashboards, you may want to leverage some of Streamlit‘s more advanced features:
- Caching: Streamlit‘s
@st.cachedecorator lets you store function results in a local cache, avoiding redundant data loading or processing when the app reruns - Session State: Streamlit maintains a session state dictionary that can store data specific to each user of your app, enabling features like pagination and user-specific recommendations
- Forms and Buttons: In addition to input widgets, Streamlit offers stateful
st.formandst.buttoncomponents for handling form submission and button clicks - Custom Components: For ultimate flexibility, you can create your own custom components with HTML/JavaScript and integrate them in your Streamlit app
Streamlit also has a growing ecosystem of third-party components and integrations built by the community. It‘s worth browsing the Streamlit Components Gallery to see if existing packages can help accelerate your dashboard development.
Example Dashboards
Need some inspiration for your own dashboards? Here are a few examples of informative and visually compelling dashboards built with Streamlit:
- A COVID-19 tracking dashboard pulling live data from the Johns Hopkins University dataset: Link
- An interactive neural network playground for visualizing model training in the browser: Link
- A fun "Bad Password Detector" app showcasing various Streamlit input and output widgets: Link
You can find many more examples on the Streamlit Community page, or by searching GitHub for Streamlit apps. Reverse-engineering others‘ code is a great way to pick up tips and tricks!
Tips and Best Practices
To create effective dashboards that deliver value to your users, keep these tips in mind:
- Know your audience: Design with your end users and their goals in mind. What questions are they trying to answer? What data and insights would be most impactful for them?
- Keep it focused: Resist the urge to cram in every possible chart and metric. Curate your content to tell a coherent story and highlight key takeaways.
- Make it interactive: Take advantage of Streamlit‘s widgets and interactive components to let users engage with the data and uncover their own insights.
- Optimize performance: Be mindful of app loading and reaction speed, especially for large datasets. Use caching, loading indicators and other techniques to ensure a snappy user experience.
- Gather feedback: Share your dashboard with others and solicit their input. User testing can reveal usability issues and spark ideas for new features and enhancements.
Most importantly, iterate! Dashboards are never truly "done". As you collect feedback and learn more about your data and your users‘ needs, continue refining and expanding your dashboard to maximize its impact.
Conclusion
Interactive dashboards are invaluable tools for making sense of data and driving better decisions. With Streamlit and Python, data scientists and analysts can build powerful, professional dashboards quickly and easily, without needing expertise in web development.
The simple, flexible syntax of Streamlit combined with the expressiveness of Python and its data science ecosystem offers everything you need to turn your analyses into impactful web apps. And the Streamlit community offers a wealth of resources—components, templates, tutorials and sample code—to support you on your dashboard development journey.
So give Streamlit a try for your next data visualization project. With a bit of creativity and iteration, you can build interactive dashboards that make your data truly sing!