Introduction to Streamlit: Building Interactive Web Apps using Python
Web applications are used to create and deploy interactive software providing a platform-agnostic way for users to interact with an application via a web browser. A popular library for creating web applications is Streamlit, created by Adrien Treuille and Thiago Teixeira in 2019.
What is Streamlit?
Streamlit (https://streamlit.io/) is an open-source Python library that makes it easy to create interactive web applications. It was designed to be simple and easy to use, with a focus on building the application and not the underlying infrastructure.
When should you use Streamlit?
There are many situations where Streamlit can be a useful tool for building web applications in Python. These include:
- Prototyping and developing small-scale applications quickly
- Creating interactive dashboards for data exploration and visualization
- Building custom interactive tools for data analysis
- Creating web-based interfaces for machine learning models or data pipelines
What are the pros and cons of using Streamlit?
Like any tool, Streamlit has its own set of pros and cons that you should consider when deciding whether it is the right fit for your project.
Pros:
- Simplicity: Streamlit is designed to be simple and easy to use, it is a “single-file” solution, meaning you can create a complete web application with just a single Python script.
- Focus on interactivity: Streamlit has a number of built-in components for visualizing data, which makes it well-suited for building interactive dashboards and tools for data exploration and analysis.
- Large ecosystem of libraries: Python has a large ecosystem of libraries and frameworks that can be used with Streamlit. Popular visualization libraries (Matplotlib, Seaborn, and Plotly) can all be utilized when building advanced web applications.
Cons:
- Limited to Python: Streamlit is a Python library, therefore it can only be used to build web applications in Python. If you need to build an application in a different language, you will need to use a different framework.
- Limited to small-scale apps: Streamlit is designed for building small-scale, interactive web applications. If you’re building a larger or more complex application, you’ll need to consider an alternative framework such as Django or Flask.
- Limited customization: While Streamlit does allow customization, it is not as flexible as other web frameworks. Should you require more control over the underlying infrastructure, you may need to consider a different framework.
Getting started with Streamlit
To get started with Streamlit, you first need to install it using pip:
pip install streamlit
Once Streamlit is installed, you can create a new Python script and import the library:
import streamlit as st
For the purpose of this article, we will be using the gapminder dataset from the Plotly library. The gapminder dataset includes information on various indicators such as GDP, life expectancy, population, and others for countries around the world between the years 1952 and 2007.
Firstly, let’s import the gapminder dataset:
import plotly.express as px
# Import the gapminder dataset
df = px.data.gapminder()
The next step is to create a title for your application, we will also create a series of filters that will be applied to all visualizations within the web application.
# Create a title for the application
st.title("Gapminder Data Exploration")
# Create a sidebar with various filters
year_min = st.sidebar.slider("Year Min", 1952, 2007, 1952)
year_max = st.sidebar.slider("Year Max", 1952, 2007, 2007)
country = st.sidebar.multiselect("Country", df["country"].unique())
log_y = st.sidebar.radio("Y-axis Scale", ["Linear", "Log"])
A slider
widget is implemented to define the minimum and maximum years you would like to visualize. Countries are selected using a multiselect
widget, this allows the user to select more than one country at a time. Finally, the Y-axis Scale filter is using a radio
widget, this allows the user to select whether they would like to view the visuals using a log scale or not.
For more information on the different widgets available when using Streamlit, click here.
To apply these filters, we have to filter the initial dataset using the variables created:
# Filter the dataset based on the selected values
filtered_df = df[
(df["year"] >= year_min) & (df["year"] <= year_max) &
df["country"].isin(country)
]
Now we have our filtered dataset, we are ready to begin plotting our data. The plot we will create is a scatter plot mapping GDP per capita against life expectancy. We will create a legend for the plot highlighting each country, compose a title and rename the axis titles for better presentation.
# Create a scatter plot of GDP per capita vs life expectancy
fig1 = px.scatter(
filtered_df,
x="gdpPercap",
y="lifeExp",
size="pop",
color="country",
title="Life Expectancy vs GDP per Capita",
)
# Update the layout to rename the axes
fig1.update_layout(
xaxis=dict(title="GDP per Capita"), yaxis=dict(title="Life Expectancy")
)
# Set the y-axis scale to log if selected
if log_y == "Log":
fig1.update_layout(yaxis_type="log")
# Display the plot
st.plotly_chart(fig1)
# Display some text explaining the chart
st.markdown(
"""
This chart shows the relationship between GDP per capita and
life expectancy for different countries. You can
use the filters in the sidebar to adjust the year range and country,
and to change the y-axis scale.
"""
)
For more information on the different plots available using Streamlit, click here.
As well as creating the plot, we can implement the st.markdown
function to add text to the web application explaining what the plot is displaying. Adding text can enhance the user's experience as they navigate the app, especially when developing more complex, multipage applications.
After executing the code above, your Streamlit web application will look like the following:
To launch your Streamlit application, run the following command via your terminal:
streamlit run streamlit-app.py
Once executed, you will be provided with both local and network URLs. A tab will open in your default browser allowing you to interact with your web application.
Conclusion
Streamlit is a popular Python library for creating interactive web applications. Its simplicity and focus on building applications while not having to worry about underlying infrastructure makes it a great choice when developing small-scale applications. As with most tools, Streamlit has its limitations, being a Python-only tool and not being suitable when developing larger/more complex applications often results in having to use an alternative framework. It is important to always evaluate the pros and cons of Streamlit when deciding if it is the right fit for your project.