"Create interactive web apps with Streamlit from scratch."
By Niraj Ghetiya
09/28/2024
Streamlit is an open-source framework designed specifically for machine learning and data science projects, enabling developers and data scientists to create beautiful, interactive web applications quickly and easily using Python. Unlike traditional web frameworks, Streamlit abstracts much of the complexity, allowing you to focus on what really matters: your data and insights.
In this comprehensive guide, we will explore Streamlit in detail, covering everything from installation to advanced features, complete with code examples that will help you get started on your own applications.
Streamlit is a powerful framework that allows developers to create web applications directly from Python scripts. It was designed with the data scientist in mind, providing a simple way to create interactive tools without requiring extensive knowledge of web development technologies like HTML, CSS, or JavaScript. With Streamlit, you can turn your data scripts into shareable web apps in just a few lines of code.
Quick Setup: Streamlit apps can be created with minimal setup. You don’t need to configure servers or databases.
Real-Time Interaction: Streamlit supports interactive widgets that allow users to manipulate data in real-time, making it ideal for exploratory data analysis.
Automatic UI Generation: Streamlit automatically updates the user interface based on changes in your code, allowing for rapid iteration and prototyping.
Rich Visualizations: Streamlit integrates seamlessly with libraries like Matplotlib, Plotly, and Altair, enabling you to create stunning visualizations with ease.
Deployment Flexibility: You can deploy Streamlit apps on various platforms, including Streamlit Cloud, Heroku, AWS, and Google Cloud.
To get started with Streamlit, you need to install it via pip. Open your terminal or command prompt and run the following command:
pip install streamlit
After installation, you can verify that Streamlit is working by running the demo application:
streamlit hello
This command opens a new tab in your web browser showcasing a sample app demonstrating various features of Streamlit.
Creating a basic Streamlit app is straightforward. You just need to write a Python script. Here’s how to create a simple app that displays a title and some text.
import streamlit as st
# Title of the web app
st.title('My First Streamlit App')
# Displaying text
st.write('Hello, welcome to my first Streamlit app!')
To run this app, save it as app.py
and execute the following command in your terminal:
streamlit run app.py
Your app will now be running, and you can access it in your browser at http://localhost:8501
.
Streamlit allows you to enhance your app's interactivity with various widgets. Here are some of the most commonly used widgets:
Sliders let users select a value from a specified range.
import streamlit as st
st.title('Slider Example')
# Slider
number = st.slider('Select a number:', 1, 100, 50)
st.write(f'The number you selected is {number}')
Buttons trigger actions when clicked.
if st.button('Click Me'):
st.write('Button clicked!')
Text input allows users to enter text.
user_input = st.text_input('Enter your name:')
st.write(f'Hello, {user_input}')
Checkboxes can be used for boolean selections.
if st.checkbox('Show/Hide'):
st.write('Checkbox is checked!')
Streamlit makes it easy to display various types of data, including tables, charts, and images.
You can display Pandas DataFrames directly in your Streamlit app:
import pandas as pd
import streamlit as st
# Sample DataFrame
data = {'Column A': [1, 2, 3, 4], 'Column B': [10, 20, 30, 40]}
df = pd.DataFrame(data)
# Display DataFrame
st.write(df)
Streamlit allows you to create various types of charts using libraries like Matplotlib, Plotly, and Altair. Here’s an example using Matplotlib:
import matplotlib.pyplot as plt
import numpy as np
# Generate some data
x = np.linspace(0, 10, 100)
y = np.sin(x)
# Create a plot
plt.plot(x, y)
plt.title('Sine Wave')
plt.xlabel('x')
plt.ylabel('sin(x)')
# Display the plot
st.pyplot(plt)
You can also display images using the st.image()
function:
from PIL import Image
# Load an image
img = Image.open('path_to_your_image.jpg')
# Display the image
st.image(img, caption='Sample Image')
Visualizations play a crucial role in data analysis and storytelling. Streamlit provides excellent support for visualizations through various libraries.
Here’s how you can create an interactive Plotly chart in your Streamlit app:
import plotly.express as px
import streamlit as st
# Sample data
df = px.data.iris()
# Create a Plotly scatter plot
fig = px.scatter(df, x='sepal_width', y='sepal_length', color='species', title='Iris Dataset')
# Display the Plotly figure
st.plotly_chart(fig)
Altair is another powerful visualization library that integrates seamlessly with Streamlit:
import altair as alt
import pandas as pd
import streamlit as st
# Sample data
data = pd.DataFrame({
'x': [1, 2, 3, 4, 5],
'y': [2, 3, 5, 7, 11]
})
# Create an Altair line chart
chart = alt.Chart(data).mark_line().encode(x='x', y='y')
# Display the Altair chart
st.altair_chart(chart, use_container_width=True)
Streamlit provides various options to customize the layout of your application, making it more user-friendly.
You can create multiple columns for a better arrangement of widgets and content.
col1, col2 = st.columns(2)
with col1:
st.write("This is column 1")
with col2:
st.write("This is column 2")
Expanders allow you to hide content until the user decides to view it.
with st.expander('Expand for more info'):
st.write('Here is some additional information.')
Tabs can be used to organize content into separate views.
tab1, tab2 = st.tabs(['Tab 1', 'Tab 2'])
with tab1:
st.write('This is content for Tab 1.')
with tab2:
st.write('This is content for Tab 2.')
Streamlit can handle user inputs effectively, allowing for dynamic applications. Here’s an example where you can generate a simple calculator app:
import streamlit as st
st.title('Simple Calculator')
# Inputs
num1 = st.number_input('Enter first number:', value=0)
num2 = st.number_input('Enter second number:', value=0)
# Operation selection
operation = st.selectbox('Select operation:', ['Add', 'Subtract', 'Multiply', 'Divide'])
# Perform calculation
if st.button('Calculate'):
if operation == 'Add':
result = num1 + num2
elif operation == 'Subtract':
result = num1 - num2
elif operation == 'Multiply':
result = num1 * num2
elif operation == 'Divide':
if num2 != 0:
result = num1 / num2
else:
result = 'Cannot divide by zero!'
st.write(f'Result: {result}')
Once your Streamlit app is ready, you can deploy it for others to use. Here are some popular deployment options:
You can also deploy Streamlit
apps using Heroku. Here’s a brief overview:
requirements.txt
: List all your dependencies.Procfile
: Add the following line:
web: streamlit run app.py
For more control over the environment, you can containerize your Streamlit app using Docker:
Dockerfile
:
FROM python:3.9
WORKDIR /app
COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt
COPY . .
CMD ["streamlit", "run", "app.py", "--server.port=8501", "--server.address=0.0.0.0"]
docker build -t my-streamlit-app .
docker run -p 8501:8501 my-streamlit-app
Here are a few ideas for real-world applications you can build with Streamlit:
Here’s a simple example of a Streamlit app that allows users to input features and predict the species of an Iris flower using a pre-trained model:
import streamlit as st
import pickle
import numpy as np
# Load pre-trained model
model = pickle.load(open('iris_model.pkl', 'rb'))
st.title('Iris Flower Prediction App')
# Inputs
sepal_length = st.number_input('Sepal Length (cm)', min_value=0.0)
sepal_width = st.number_input('Sepal Width (cm)', min_value=0.0)
petal_length = st.number_input('Petal Length (cm)', min_value=0.0)
petal_width = st.number_input('Petal Width (cm)', min_value=0.0)
# Prediction
if st.button('Predict'):
features = np.array([[sepal_length, sepal_width, petal_length, petal_width]])
prediction = model.predict(features)
st.write(f'Predicted Species: {prediction[0]}')
Streamlit is a fantastic tool for anyone looking to turn data scripts into interactive web applications quickly. Its ease of use and flexibility make it an excellent choice for data scientists and developers alike.
In this guide, we covered the basics of Streamlit, including installation, creating your first app, adding interactivity, displaying data and visualizations, handling user input, and deploying your applications. With these skills, you are well on your way to creating compelling web applications that showcase your data and insights.
Now it's time to experiment and build your own applications. Happy coding!