Mastering Streamlit: Essential Commands for Interactive Apps
Streamlit has become a go-to framework for many engineers and developers looking to turn their data scripts into shareable web apps quickly. In this guide, we’ll walk you through a series of commonly used Streamlit commands that are essential for anyone looking to create interactive web applications quickly and efficiently.
1. Getting Started with Streamlit
Before you dive into the specific commands, ensure you have Streamlit installed:
pip install streamlit
Running your first Streamlit app is as simple as:
streamlit run your_script.py
2. Displaying Data
One of the core features of Streamlit is its ability to handle and display data effortlessly.
st.dataframe
Use st.dataframe to display tables. It's versatile, supporting inputs from Pandas, PyArrow, Snowpark, and PySpark.
def load_data():
return pd.read_excel('sales.xlsx', header = 0)
data = load_data()
st.dataframe(data)
st.data_editor
Edit dataframes interactively right in your app with st.data_editor, allowing for a hands-on approach to data manipulation.
st.data_editor(data, num_rows="dynamic")
This setting permits users to dynamically add or delete rows within the data editor, providing a more flexible editing experience.
3. Visualizing Data
st.image
Display images using st.image. It supports various formats and customization options.
from PIL import Image
image = Image.open('New Jersey.jpg')
st.image(image, caption='The Garden State of USA')
st.map
Visualize geographical data with st.map, turning coordinates into compelling, interactive maps.
map_df = pd.DataFrame({'lat': [40.3573], 'lon': [-74.6672]})
st.map(map_df)
st.bar_chart
The st.bar_chart function in Streamlit is a quick and easy way to display bar charts in your application. It’s part of Streamlit’s ability to create interactive and visually appealing web apps using simple Python scripts.
df = df.set_index('body_mass')
# Plotting with st.bar_chart
st.bar_chart(data=df['year'], width=0, height=0, use_container_width=True)
Reference — other chart elements
4. Interactivity and Widgets
Streamlit’s widgets add interactivity, allowing users to input and control the app’s data and flow.
st.audio and st.video
Embed audio and video files with st.audio and st.video.
st.audio(data, format="audio/wav")
st.video(data, format="video/mp4")
st.tabs
Organize your app into tabbed sections with st.tabs, making navigation and organization much cleaner
tab1, tab2, tab3 = st.tabs(['Tab 1', 'Tab 2', 'Tab 3'])
with tab1:
st.write("This is tab 1")
st.multiselect
Allow users to select multiple options from a dropdown with st.multiselect.
st.multiselect("select columns", data.columns, default= list(data.columns))
Adjusting the dropdown where user must be able to select all the values in multiselect. When the option “All” is selected, you’re overriding the variable to be a list containing all options in the dropdown.
selected_option = st.multiselect("Select one or more options:",['A', 'B', 'C', 'All'])
if "All" in selected_option:
selected_option = ['A', 'B', 'C']
selected_option
st.download_button
When you would like to provide a way for your users to download a file directly from your app, you can utilize the st.download_button feature.
#converting the DataFrame to a CSV string
csv_data = data.to_csv(index=False)
csv_data_bytes = csv_data.encode('utf-8')
st.download_button(
label = "Download data as CSV file",
data = csv_data_bytes,
file_name = "GI_df.csv",
mime = "text/csv",
)
st.link_button
The st.link_button feature in Streamlit allows users to navigate to a specified URL in a new browser tab when clicked
st.link_button("Go to Kaggle datasets", "https://www.kaggle.com/datasets")
st.file_uploader
To allow users to upload files with a specific size limit, you can use st.file_uploader.
uploaded_files = st.sidebar.file_uploader(
label="Upload pdf, word, or txt files", type=["pdf", "doc", "docx", "txt"], accept_multiple_files=True
)
if not uploaded_files:
st.info("Please upload pdf, word, or txt documents to continue.")
st.stop()
st.set_page_config
This function can be used to set the page title, layout, initial sidebar state, page icon, and more. It’s important to note that st.set_page_config should be called only once, at the top of your main script.
st.set_page_config(page_title="Streamlit web app", page_icon="🦜", layout='wide')
st.option_menu
streamlit-option-menu allows you to create a menu bar with options that users can select from. When users select an option, you can display different content or perform different actions based on the selection.
pip install streamlit-option-menu
selected = option_menu(None, ["Home", "Upload", "Tasks", “QA”, “Overall summary”
,”Settings”],
icons=['house', 'cloud-upload', "list-task", 'question-diamond-fill' , 'card-list' ,'gear'],
menu_icon="cast", default_index=0, orientation="horizontal",
styles={
"container": {"padding": "0!important", "background-color": "#fafafa"},
"icon": {"color": "orange", "font-size": "25px"},
"nav-link": {"font-size": "25px", "text-align": "left", "margin":"0px", "--hover-color": "#eee"},
"nav-link-selected": {"background-color": "green"}
}
)
st.stoggle
st.stoggle is used to create a toggle button in your Streamlit app.
from streamlit_extras.stoggle import stoggle
stoggle(
"Click Me 👈",
""" Happy Streamlit’ing! 😂 🦊 🐻 🐼""",
)
st.number_input
The st.number_input function in Streamlit creates a numeric input widget allowing users to input numbers. It supports both float and integer inputs and provides functionality for setting a range of values, step increments/decrements, and default values.
https://docs.streamlit.io/library/api-reference/widgets/st.number_input
number = st.number_input("Insert a number", value=None, placeholder="Type a number...")
st.text_input
The st.text_input function in streamlit is used to create a single-line text input widget where users can enter input text.
st.text_input("🗣️ Ask me a question here: ", placeholder = 'Enter your question here', value="")
st.text_area
The st.text_area function in streamlit creates a multi-line text input box, allowing users to enter longer blocks of text.
# Multi-line text input
user_feedback = st.text_area("Feedback", "Type your feedback here...")
st.date_input
The st.date_input function in streamlit allows users to input dates through a calendar picker interface.
st.date_input(f"Start Date", datetime.date(2024, 1, 1))
st.radio
The st.radio function in Streamlit creates a set of radio buttons, which are exclusive selection options where the user can select only one option from a list.
# Define the options for the radio buttons
options = ['Jan', 'Feb', 'March']
# Create the radio button with the options
selected_option = st.radio("Choose an option:", options)
st.slider
The st.slider function in Streamlit creates a slider widget allowing users to select from a range of values by sliding.
values = st.slider(
'Select a range of values',
0.0, 100.0, (25.0, 75.0))
st.write('Values:', values)
5. Refresh or Reset your Streamlit app
Below method uses the pyautogui library to simulate keyboard shortcuts.
import pyautogui
if st.button("Reset"): # refreshes the entire page and removes cache
pyautogui.hotkey("ctrl", "F5")
Below method uses the streamlit_js_eval function to execute JavaScript code that refreshes the page.
from streamlit_js_eval import streamlit_js_eval
if st.sidebar.button("Reset filters"): # refreshes the entire page and removes cache
streamlit_js_eval(js_expressions="parent.window.location.reload()")
Below code uses an experimental feature of Streamlit to rerun the script from the top.
if st.sidebar.button("Reset filters"): # just reloads the page doesn’t remove cache
st.experimental_rerun()
6. Advanced Features
st.cache_data and st.cache_resource
Speed up your apps by caching expensive computation results.
st.cache_data is the recommended way to cache computations that return data: loading a DataFrame from CSV, transforming a NumPy array, querying an API, or any other function that returns a serializable data object. It creates a new copy of the data at each function call, making it safe against mutations.
@st.cache_data # 👈 Add the caching decorator
def get_data(query):
connection = db_connection()
try:
df = pd.read_sql(query, connection)
return df
except Exception as e:
st.error(f'Error occurred while connecting to the database: {e}')
st.stop()
return None
st.cache_resource is the recommended way to cache global resources like ML models or database connections – unserializable objects that you don't want to load multiple times. Using it, you can share these resources across all reruns and sessions of an app without copying or duplication.
@st.cache_resource
def init_connection():
host = ""
database = ""
user = ""
password = ""
return psycopg2.connect(host=host, database=database, user=user, password=password)
conn = init_connection()
Refer — https://docs.streamlit.io/library/advanced-features/caching
Session State
Session state is persistent across reruns of the app, which is particularly useful for user interactions and data selections in Streamlit. This code effectively uses session state to remember the user’s choices and update them as needed.
if 'filters' not in st.session_state:
st.session_state.filters = filters
if st.session_state.filters.get(column) is None:
default_values = unique_values
else:
default_values = st.session_state.filters[column]
def get_new_defalut_values_list():
st.session_state.filters[column] = default_values
st.session_state.filters[column] = right.multiselect(
f"{column}",
unique_values,
default= [val for val in default_values if val in unique_values],
key=f"{random_key_base}_{column}",
on_change=get_new_defalut_values_list
)
7. Theming and Customization
Personalize your app’s look and feel with Streamlit’s theming capabilities.
Streamlit Theming now allows you to easily change the color scheme and fonts in your app without ever having to touch any HTML or CSS.
# .streamlit/config.toml
[theme]
primaryColor = "#f63366"
backgroundColor = "#ffffff"
secondaryBackgroundColor = "#f0f2f6"
textColor = "#262730"
# .streamlit/config.toml
[theme]
base="light"
primaryColor="MediumSeaGreen" # vibrant blue
secondaryBackgroundColor="light gray" # light gray
textColor="black" #dark text on a light background
8. Conclusion
Streamlit offers a rich set of commands to build interactive and beautiful data apps. With the commands and functions highlighted in this guide, you’re well-equipped to create dynamic and user-friendly applications. Dive into the Streamlit documentation to explore more and keep experimenting with different widgets and features to find what works best for your projects. Happy Streamliting!
If you like the blog, make sure to clap for the story and support me👏
View more content on my medium profile 📰
LinkedIn Profile: https://www.linkedin.com/in/saiharish-ch/