- Introduction to Streamlit
- Getting Started
- Core Concepts
- Widgets and Components
- Data Visualization
- Advanced Features
- Best Practices
- Deployment
- Learning Paths
- Resources and Community
Streamlit is an open-source Python library that makes it easy to create and share beautiful, custom web apps for machine learning and data science. It allows you to turn Python scripts into interactive web applications with just a few lines of code.
- Simple to Use: Write Python code and see results instantly
- Interactive: Built-in widgets for user input and interaction
- Fast Development: No frontend knowledge required
- Data Science Focused: Perfect for ML models, data analysis, and visualizations
- Easy Deployment: Deploy to the web with one command
- Rapid Prototyping: Build apps in minutes, not hours
- Python Native: No need to learn JavaScript or HTML
- Rich Ecosystem: Integrates with popular data science libraries
- Active Community: Strong support and regular updates
# Install Streamlit
pip install streamlit
# Verify installation
streamlit --versionimport streamlit as st
# Page configuration
st.set_page_config(
page_title="My First App",
page_icon=":wave:",
layout="centered"
)
# Main content
st.title("Hello, Streamlit!")
st.write("Welcome to my first Streamlit application!")
# Interactive element
name = st.text_input("Enter your name:")
if name:
st.write(f"Hello, {name}! 馃憢")# Save the code as app.py and run:
streamlit run app.pyEvery Streamlit app follows a simple structure:
import streamlit as st
# 1. Page configuration
st.set_page_config(...)
# 2. Main content
st.title("Your App Title")
st.write("Your content here")
# 3. Interactive elements
user_input = st.text_input("Enter something:")
# 4. Logic and processing
if user_input:
# Process the input
result = process_input(user_input)
st.write(f"Result: {result}")- Script Runs: Streamlit executes your script from top to bottom
- Widgets Created: Interactive elements are rendered on the page
- User Interaction: When users interact with widgets, the script reruns
- State Management: Streamlit maintains state between interactions
- Reactive: Apps automatically update when inputs change
- Stateful: Maintains data between interactions
- Component-Based: Built from reusable widgets and components
# Single line text
name = st.text_input("Enter your name:", placeholder="John Doe")
# Multi-line text
description = st.text_area("Description:", height=100)
# Password input
password = st.text_input("Password:", type="password")# Number input
age = st.number_input("Age:", min_value=0, max_value=120, value=25)
# Slider
temperature = st.slider("Temperature:", min_value=-50, max_value=100, value=20)
# Range slider
price_range = st.slider("Price range:", min_value=0, max_value=1000, value=(100, 500))# Date picker
date = st.date_input("Select a date:")
# Time picker
time = st.time_input("Select a time:")# Single file
uploaded_file = st.file_uploader("Choose a file:", type=['csv', 'txt'])
# Multiple files
uploaded_files = st.file_uploader("Choose files:", accept_multiple_files=True)# Selectbox
option = st.selectbox("Choose an option:", ["Option 1", "Option 2", "Option 3"])
# Multiselect
options = st.multiselect("Choose options:", ["A", "B", "C", "D"])
# Radio buttons
choice = st.radio("Select one:", ["Yes", "No", "Maybe"])# Simple checkbox
agree = st.checkbox("I agree to the terms")
# Checkbox with default
show_data = st.checkbox("Show data", value=True)# Regular button
if st.button("Click me"):
st.write("Button clicked!")
# Primary button
if st.button("Submit", type="primary"):
st.success("Form submitted!")
# Download button
st.download_button(
label="Download data",
data=csv_data,
file_name="data.csv",
mime="text/csv"
)# Basic text
st.write("This is regular text")
# Markdown
st.markdown("**Bold text** and *italic text*")
# Code
st.code("print('Hello, World!')")
# JSON
st.json({"name": "John", "age": 30})# Dataframe
st.dataframe(df)
# Table
st.table(df.head())
# Metric
st.metric("Temperature", "24掳C", "2掳C")import pandas as pd
import numpy as np
# Sample data
data = pd.DataFrame({
'x': np.random.randn(100),
'y': np.random.randn(100)
})
# Line chart
st.line_chart(data)
# Bar chart
st.bar_chart(data)
# Area chart
st.area_chart(data)import plotly.express as px
import plotly.graph_objects as go
# Scatter plot
fig = px.scatter(data, x='x', y='y', title='Scatter Plot')
st.plotly_chart(fig)
# Line plot
fig = px.line(data, x='x', y='y', title='Line Plot')
st.plotly_chart(fig)
# Bar plot
fig = px.bar(data, x='x', y='y', title='Bar Plot')
st.plotly_chart(fig)
# 3D scatter
fig = px.scatter_3d(data, x='x', y='y', z='z')
st.plotly_chart(fig)import matplotlib.pyplot as plt
# Create plot
fig, ax = plt.subplots()
ax.plot(data['x'], data['y'])
ax.set_title('Matplotlib Plot')
st.pyplot(fig)import folium
from streamlit_folium import st_folium
# Create map
m = folium.Map(location=[45.5236, -122.6750], zoom_start=13)
folium.Marker([45.5236, -122.6750], popup="Portland").add_to(m)
st_folium(m, width=700, height=500)# Initialize session state
if "counter" not in st.session_state:
st.session_state.counter = 0
# Use session state
if st.button("Increment"):
st.session_state.counter += 1
st.write(f"Counter: {st.session_state.counter}")
# Clear session state
if st.button("Reset"):
st.session_state.clear()@st.cache_data
def load_data():
"""Load and cache expensive data operations"""
return pd.read_csv("large_file.csv")
@st.cache_resource
def load_model():
"""Load and cache ML model"""
return joblib.load("model.pkl")
# Use cached functions
data = load_data()
model = load_model()with st.form("my_form"):
name = st.text_input("Name")
email = st.text_input("Email")
age = st.number_input("Age", min_value=0, max_value=120)
submitted = st.form_submit_button("Submit")
if submitted:
if name and email and age > 0:
st.success("Form submitted successfully!")
else:
st.error("Please fill all fields correctly")# Create columns
col1, col2, col3 = st.columns(3)
with col1:
st.write("Column 1")
st.button("Button 1")
with col2:
st.write("Column 2")
st.button("Button 2")
with col3:
st.write("Column 3")
st.button("Button 3")# Create tabs
tab1, tab2, tab3 = st.tabs(["Data", "Charts", "Settings"])
with tab1:
st.write("Data tab content")
st.dataframe(df)
with tab2:
st.write("Charts tab content")
st.line_chart(data)
with tab3:
st.write("Settings tab content")
st.slider("Threshold", 0, 100, 50)# Sidebar for controls
with st.sidebar:
st.header("Settings")
threshold = st.slider("Threshold", 0, 100, 50)
show_data = st.checkbox("Show data", value=True)
if st.button("Reset"):
st.session_state.clear()with st.expander("Click to see more details"):
st.write("This is hidden content that can be expanded.")
st.dataframe(df.head())# Separate functions for different components
def load_data():
"""Load and cache data"""
pass
def create_sidebar():
"""Create sidebar controls"""
pass
def display_charts(data):
"""Display visualizations"""
pass
def main():
"""Main application logic"""
data = load_data()
create_sidebar()
display_charts(data)
if __name__ == "__main__":
main()try:
result = risky_operation()
st.success("Operation successful!")
except Exception as e:
st.error(f"An error occurred: {str(e)}")
st.info("Please try again or contact support")# Use caching for expensive operations
@st.cache_data(ttl=3600) # Cache for 1 hour
def expensive_computation(data):
# Heavy computation here
return result
# Use containers for better organization
with st.container():
st.write("Grouped content")
# Avoid unnecessary reruns
if st.button("Process"):
with st.spinner("Processing..."):
result = expensive_computation(data)
st.success("Done!")# Loading states
with st.spinner("Loading data..."):
data = load_data()
# Progress bars
progress_bar = st.progress(0)
for i in range(100):
progress_bar.progress(i + 1)
# Success/error messages
st.success("Operation completed successfully!")
st.error("Something went wrong!")
st.warning("Please check your input.")
st.info("Here's some information.")# Development mode
streamlit run app.py --server.port 8501
# Production mode
streamlit run app.py --server.headless true- Push your code to GitHub
- Go to share.streamlit.io
- Connect your GitHub repository
- Deploy automatically
# Create Procfile
echo "web: streamlit run app.py --server.port=\$PORT --server.address=0.0.0.0" > Procfile
# Deploy
heroku create your-app-name
git push heroku mainFROM python:3.9-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
EXPOSE 8501
CMD ["streamlit", "run", "app.py", "--server.port=8501", "--server.address=0.0.0.0"]-
Week 1: Basic Streamlit concepts and widgets
- Complete official quick start tutorial
- Build simple calculator app
- Practice with different input widgets
-
Week 2: Data visualization and charts
- Learn Plotly integration
- Create dashboard with multiple charts
- Practice with real datasets
-
Week 3: Layout and organization
- Master columns, tabs, and expanders
- Build multi-page applications
- Learn session state management
-
Week 4: Deployment and best practices
- Deploy to Streamlit Cloud
- Learn caching and performance
- Build a complete project
-
Advanced Widgets and Interactions
- Custom components
- Advanced forms and validation
- Real-time updates
-
Machine Learning Integration
- Model deployment patterns
- Interactive training interfaces
- Model comparison tools
-
Production Applications
- Error handling and logging
- Performance optimization
- Security considerations
-
Custom Components
- Building custom Streamlit components
- JavaScript integration
- Advanced UI patterns
-
Scalable Applications
- Database integration
- API development
- Microservices architecture
-
Enterprise Features
- Authentication and authorization
- Multi-user applications
- Advanced deployment strategies
- Streamlit Documentation: Complete API reference
- Streamlit Cheat Sheet: Quick reference
- Streamlit Gallery: Inspirational examples
- Streamlit Community: Community forum
- Streamlit Discord: Real-time chat
- Reddit r/streamlit: Community discussions
- Stack Overflow: Q&A platform
- Streamlit Official: Official tutorials
- Data Professor: Streamlit tutorials
- Coding Is Fun: Streamlit projects
- "Streamlit for Data Science" by Tyler Richards
- "Building Data Science Applications with Streamlit" by Marc Skov Madsen
- Coursera/Udemy Streamlit courses
-
Personal Dashboard
- Weather app with API integration
- Personal finance tracker
- Task management app
-
Data Analysis Tools
- CSV file analyzer
- Basic statistics calculator
- Data visualization explorer
-
Machine Learning Apps
- Image classification interface
- Text sentiment analyzer
- Recommendation system
-
Business Applications
- Sales dashboard
- Inventory management
- Customer feedback analyzer
-
Full-Stack Applications
- E-commerce platform
- Social media dashboard
- Real-time monitoring system
-
Specialized Tools
- Financial modeling app
- Scientific calculator
- Data pipeline interface
This learning guide provides a comprehensive introduction to Streamlit development. For the latest updates and advanced features, always refer to the official Streamlit documentation.