xavier collantes

Streamlit Data Visualization Cheat Sheet

By Xavier Collantes

1/26/2024


Quickly create front ends from Python data notebooks. Official cheat sheet: streamlit.io/library/cheatsheet.

Quick start

Bash
1# Install streamlit
2python3 -m venv env
3env/bin/pip install pip --upgrade
4env/bin/pip install streamlit
5
6# Create Python files
7touch main.py
8
9# Add contents to file
10
11# Run file
12env/bin/streamlit run main.py
13
snippet hosted withby Xavier

Example

🐍
Python3
1import streamlit as st
2import pandas as pd
3import numpy as np
4
5def main() -> None:
6  st.title("Quick start example")
7  st.header("Show graphs")
8  st.subheader("Graphs")
9  st.write("**Markdown supported**")
10
11  # Generate sample data for map
12  df = pd.DataFrame(
13    [[(c[0] / 100) + 47.66676293891633, ((c[1] / 100) + 117.40216206237741) * -1]
14     for c in np.random.randn(20, 2)],
15    columns=["lat", "lon"]
16  )
17  st.map(df)
18
19  if st.checkbox("Show data"):
20    st.write(df)
21
22
23if __name__ == "__main__":
24  print("Running")
25  main()
26
snippet hosted withby Xavier

Config

.streamlit/config.toml
toml
1[server]
2port = 80
3
4[browser]
5gatherUsageStats = false
6
snippet hosted withby Xavier

Import data

Use data like you would in Python Pandas.
🐍
Python3
1csv_df = pd.read_csv(
2  "https://raw.githubusercontent.com/xcollantes/stock_analysis_dataset/main/us_tickers.csv"
3)
4st.write(csv_df)
5
snippet hosted withby Xavier

Caching

Save resources on costly API calls. Streamlit runs the whole code every time a user interacts. Caching documentation
Use @st.cache_data decorator on a function to save the contents of the function such as DataFrames and any serializable data such as ints, floats, strings.
Streamlit will only run the function if either:
  • The input params are different from subsequent runs.
  • Code inside the function has changed.
@st.cache_resource is for database connections.

UI Components

Text and Display

🐍
Python3
1st.title("Main Title")
2st.header("Header")
3st.subheader("Subheader")
4st.text("Fixed-width text")
5st.markdown("**Bold** and *italic* text")
6st.latex(r"\int_a^b x^2 dx")
7st.code("print('Hello world')", language="python")
8
snippet hosted withby Xavier

Input Widgets

🐍
Python3
1# Text inputs
2name = st.text_input("Enter your name")
3message = st.text_area("Your message")
4number = st.number_input("Pick a number", min_value=0, max_value=100)
5
6# Selection widgets
7option = st.selectbox("Choose option", ["Option 1", "Option 2", "Option 3"])
8options = st.multiselect("Choose multiple", ["A", "B", "C"])
9slider_val = st.slider("Select value", 0, 100, 50)
10range_vals = st.slider("Select range", 0, 100, (25, 75))
11
12# Boolean inputs
13agree = st.checkbox("I agree")
14choice = st.radio("Choose one", ["Yes", "No", "Maybe"])
15
snippet hosted withby Xavier

Buttons and Actions

🐍
Python3
1if st.button("Click me"):
2  st.write("Button was clicked!")
3
4# Download button
5csv = df.to_csv(index=False)
6st.download_button("Download CSV", csv, "data.csv", "text/csv")
7
snippet hosted withby Xavier

Charts and Visualizations

🐍
Python3
1import matplotlib.pyplot as plt
2import altair as alt
3
4# Line chart
5chart_data = pd.DataFrame(np.random.randn(20, 3), columns=["a", "b", "c"])
6st.line_chart(chart_data)
7
8# Bar chart
9st.bar_chart(chart_data)
10
11# Area chart
12st.area_chart(chart_data)
13
14# Matplotlib
15fig, ax = plt.subplots()
16ax.hist(np.random.normal(1, 1, size=100), bins=20)
17st.pyplot(fig)
18
19# Altair
20chart = alt.Chart(chart_data.reset_index()).mark_circle().encode(
21  x="index", y="a", size="b", color="c", tooltip=["index", "a", "b", "c"]
22)
23st.altair_chart(chart, use_container_width=True)
24
snippet hosted withby Xavier

Session State

Store data across reruns:
🐍
Python3
1# Initialize session state
2if "counter" not in st.session_state:
3  st.session_state.counter = 0
4
5# Update state
6if st.button("Increment"):
7  st.session_state.counter += 1
8
9st.write(f"Counter: {st.session_state.counter}")
10
11# Store complex data
12if "data" not in st.session_state:
13  st.session_state.data = pd.DataFrame()
14
snippet hosted withby Xavier

Layout and Containers

🐍
Python3
1# Sidebar
2st.sidebar.title("Sidebar")
3sidebar_option = st.sidebar.selectbox("Choose", ["A", "B", "C"])
4
5# Columns
6col1, col2, col3 = st.columns([1, 2, 1])
7with col1:
8  st.write("Column 1")
9with col2:
10  st.write("Column 2")
11with col3:
12  st.write("Column 3")
13
14# Tabs
15tab1, tab2, tab3 = st.tabs(["Tab 1", "Tab 2", "Tab 3"])
16with tab1:
17  st.write("Content for tab 1")
18
19# Containers
20with st.container():
21  st.write("This is inside a container")
22
23# Expander
24with st.expander("Click to expand"):
25  st.write("Hidden content")
26
snippet hosted withby Xavier

File Operations

🐍
Python3
1# File upload
2uploaded_file = st.file_uploader("Choose a file")
3if uploaded_file is not None:
4  df = pd.read_csv(uploaded_file)
5  st.write(df)
6
7# Multiple files
8uploaded_files = st.file_uploader("Choose files", accept_multiple_files=True)
9for uploaded_file in uploaded_files:
10  st.write(f"Filename: {uploaded_file.name}")
11
12# Image upload
13image = st.file_uploader("Upload image", type=["png", "jpg", "jpeg"])
14if image is not None:
15  st.image(image, caption="Uploaded image")
16
snippet hosted withby Xavier

Forms

🐍
Python3
1with st.form("my_form"):
2  name = st.text_input("Name")
3  age = st.number_input("Age", min_value=0, max_value=120)
4  submitted = st.form_submit_button("Submit")
5
6  if submitted:
7    st.success(f"Hello {name}, you are {age} years old!")
8
9# Form with file upload
10with st.form("file_form"):
11  uploaded_file = st.file_uploader("Choose file")
12  process = st.form_submit_button("Process File")
13
snippet hosted withby Xavier

Interactive data

The user can change data to affect other parts of the visualization using st.data_editor.
🐍
Python3
1# Editable dataframe
2edited_df = st.data_editor(df)
3
4# Data editor with configuration
5edited_df = st.data_editor(
6  df,
7  column_config={
8    "price": st.column_config.NumberColumn(
9      "Price ($)",
10      help="The price in USD",
11      min_value=0,
12      max_value=1000,
13      step=1,
14      format="$%d",
15    )
16  },
17  disabled=["name"],  # Make name column read-only
18  hide_index=True,
19)
20
snippet hosted withby Xavier

Altair library

Streamlit can use the Altair library for advanced visualizations.

Chat interface

There is a chat UI where the format returns graphs: Chat message API
This could be useful when creating a chat bot which can show visualizations.
🐍
Python3
1# Chat interface example
2with st.chat_message("user"):
3  st.write("Hello 👋")
4
5with st.chat_message("assistant"):
6  st.write("Hello human")
7  st.bar_chart(np.random.randn(30, 3))
8
9# Chat input
10prompt = st.chat_input("Say something")
11if prompt:
12  st.write(f"User: {prompt}")
13
snippet hosted withby Xavier

Progress and Status

🐍
Python3
1# Progress bar
2progress_bar = st.progress(0)
3for i in range(100):
4  progress_bar.progress(i + 1)
5
6# Status indicators
7st.success("Success message")
8st.info("Info message")
9st.warning("Warning message")
10st.error("Error message")
11
12# Spinner
13with st.spinner("Loading..."):
14  time.sleep(2)
15st.success("Done!")
16
17# Balloons and snow
18st.balloons()
19st.snow()
20
snippet hosted withby Xavier

Deployment

Streamlit Cloud

  1. Push your code to GitHub
  2. Go to share.streamlit.io
  3. Connect your GitHub repository
  4. Deploy with one click

Local deployment

Bash
1# Run locally
2streamlit run app.py
3
4# Run on specific port
5streamlit run app.py --server.port 8080
6
7# Run with custom config
8streamlit run app.py --server.address 0.0.0.0
9
snippet hosted withby Xavier

Docker

dockerfile
1FROM python:3.9-slim
2
3WORKDIR /app
4COPY requirements.txt .
5RUN pip install -r requirements.txt
6
7COPY . .
8
9EXPOSE 8501
10
11CMD ["streamlit", "run", "app.py", "--server.address=0.0.0.0"]
12
snippet hosted withby Xavier

Web page

🐍
Python3
1st.set_page_config(
2  page_title="Ex-stream-ly Cool App",
3  page_icon="🧊",
4  layout="wide",
5  initial_sidebar_state="expanded",
6)
7
snippet hosted withby Xavier

Key and Secrets management

Existing secrets management tools, such as dotenv filesAWS credentials filesGoogle Cloud Secret Manager, or Hashicorp Vault, will work fine in Streamlit. We just add native secrets management for times when it's useful.

Related Articles

Related by topics:

frontend
webdev
bi
python
User Metrics With Amplitude And NextJS

Quick guide for getting started with Amplitude and NextJS.

By Xavier Collantes8/11/2025
amplitude
metrics
analytics
+4

HomeFeedback