By Xavier Collantes
1/26/2024
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
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
.streamlit/config.toml
1csv_df = pd.read_csv(
2 "https://raw.githubusercontent.com/xcollantes/stock_analysis_dataset/main/us_tickers.csv"
3)
4st.write(csv_df)
5
@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.@st.cache_resource
is for database connections.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
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
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
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
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
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
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
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
st.data_editor
.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
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
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
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
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
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
Related by topics: