Streamlit Cheatsheet
Basics
Installation
pip install streamlit
Run Application
streamlit run <filename>.py
Essential Import
import streamlit as st
import pandas as pd
import numpy as np
App Structure
Streamlit apps are executed sequentially, from top to bottom.
Widgets and Layout
Titles, Headers, and Text
st.title("App Title")
st.header("Main Header")
st.subheader("Subheader")
st.text("Regular text.")
st.markdown("Markdown **text** with _formatting_.")
Interactive Elements
Text Inputs and Number Inputs
name = st.text_input("Enter your name")
number = st.number_input("Choose a number", min_value=0, max_value=100, step=1)
Sliders
age = st.slider("Age", 0, 100, 25)
Checkboxes, Radio Buttons, and Dropdowns
agree = st.checkbox("I agree")
option = st.radio("Favorite color", ["Blue", "Green", "Red"])
selection = st.selectbox("Select an option", ["Option 1", "Option 2", "Option 3"])
Multiselect
multiselect = st.multiselect("Select multiple options", ["Option A", "Option B", "Option C"])
Buttons
if st.button("Click me"):
st.write("Button clicked!")
Displaying Data
Tables and DataFrames
data = pd.DataFrame({
"Column 1": [1, 2, 3],
"Column 2": [4, 5, 6]
})
st.write(data)
st.dataframe(data) # Interactive table
st.table(data) # Static table
Data Summary and Descriptions
st.write(data.describe()) # Statistical summary
Data Visualization
Streamlit supports a range of visualization libraries (e.g., Matplotlib, Plotly, Altair, Seaborn).
Streamlit Charts
# Example data
chart_data = pd.DataFrame(
np.random.randn(20, 3),
columns=['a', 'b', 'c']
)
st.line_chart(chart_data)
st.area_chart(chart_data)
st.bar_chart(chart_data)
Matplotlib
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.hist(data['Column 1'], bins=20)
st.pyplot(fig)
Plotly
import plotly.express as px
fig = px.scatter(data, x='Column 1', y='Column 2')
st.plotly_chart(fig)
Media and Files
Images
st.image("path_to_image.jpg", caption="Example Image", use_column_width=True)
Audio
st.audio("path_to_audio.mp3")
Video
st.video("path_to_video.mp4")
File Upload
uploaded_file = st.file_uploader("Choose a file")
if uploaded_file is not None:
data = pd.read_csv(uploaded_file)
st.write(data)
Sidebar and Layout Options
Sidebar
st.sidebar.title("Sidebar Title")
sidebar_option = st.sidebar.selectbox("Sidebar Select", ["Option A", "Option B"])
Column Layout
col1, col2 = st.columns(2)
with col1:
st.write("Column 1")
with col2:
st.write("Column 2")
Status Indicators and Progress Bars
Status Indicators
st.success("Loaded successfully")
st.error("An error occurred")
st.warning("Warning message")
st.info("Information text")
Progress Bar
import time
my_bar = st.progress(0)
for percent_complete in range(100):
time.sleep(0.01)
my_bar.progress(percent_complete + 1)
Caching for Optimization
Use caching to speed up execution by storing the output of a function.
@st.cache
def load_data():
# Time-intensive loading process
return data
Advanced Features
Conditional Display of Widgets
if st.checkbox("Show options"):
st.write("Options are displayed!")
Download Button
csv = data.to_csv(index=False)
st.download_button(
label="Download CSV",
data=csv,
file_name="data.csv",
mime="text/csv"
)
App Deployment
- Streamlit Cloud:
https://share.streamlit.io - Other options include Heroku, AWS, Google Cloud, and Docker.
Example Deployment on Streamlit Cloud
- Create Repository: Store code in a GitHub repository.
- Connect to Streamlit Cloud: Go to https://share.streamlit.io and select the repository.
- Get App URL: The app will be accessible at a public URL.