Streamlit is a widely used open-source Python framework which facilitates the creation and deployment of web apps for Machine Learning and Data Science. It enables a seamless process of developing and viewing results by allowing users to build apps just like writing Python code. This interactive loop between coding and web app visualization is a distinctive feature, making app development and result exploration efficient and effortless.
Getting Started
Table of contents
- Streamlit Methods
- Installation
- Start with hello world
- Text Elements Examples
- Widget Examples
- Input
- Button
- Checkbox
- Radio
- Slider
- Date and time
- Form
- Status
- Chart
- Data
- Chat
Streamlit Methods
Data Presentation:
- The
st.write()
function empowers you to exhibit various data formats as per the requirements. - The
st.metric()
function supports you to showcase a singular metric. - The
st.table()
function is used for rendering tabular information. - The
st.dataframe()
function is engineered to elegantly showcase pandas dataframes. - The
st.image()
function offers seamless image display for visual content. -
The
st.audio()
function takes care of audio file playback.Headers and Text Styling:
The
st.subheader()
function serves as a valuable tool for generating subheadings within your application.The
st.markdown()
function is used for enabling seamless integration of Markdown-formatted content.-
The
st.latex()
functions stands as a powerful asset for expressing mathematical equations.User Interaction:
To infuse your web application with interactive elements, Streamlit provides an array of widgets.
The
st.checkbox()
function is used for incorporating checkboxes.The
st.button()
function is used for buttons.The
st.selectbox()
function facilitates dropdown menus implementation.The
st.multiselect()
function is designed to meet multi-selection dropdown requirements.-
The
st.file_uploader()
function is used for handling file uploads.Progress Tracking:
Streamlit offers functions tailored for indicating progress.
The
st.progress()
function is used to create a dynamic progress bar.-
The
st.spinner()
function allows users to incorporate a spinner animation to denote ongoing processes.Sidebar and Form Integration:
Streamlit’s versatile capabilities extend to incorporating a sidebar to accommodate supplementary functionality.
The
st.sidebar()
function is used to seamlessly integrate elements into secondary space.-
The
st.form()
function establishes a framework for user interactions.Custom HTML and CSS Integration:
Streamlit offers provisions for embedding custom HTML and CSS to tailor your web application’s appearance and behavior.
The
st.markdown()
function enables Markdown styling.The
st.write()
function facilitates the integration of bespoke HTML components into your application.
Installation
To get started, the initial step involves the installation of Streamlit. Ensure that you have installed Python 3.7 to 3.10, along with PIP and your preferred Python Integrated Development Environment (IDE) in your machine. With these prerequisites, open your terminal and execute the following command to install Streamlit.
- Create and activate the virtual environment by executing the following command.
python -m venv venv
source venv/bin/activate #for ubuntu
venv/Scripts/activate #for windows
- Install streamlit library using pip.
pip install streamlit
Start with hello world
Initiate your Streamlit experience by delving into the pre-built “Hello World” application provided by the platform. To confirm the successful installation, execute the following command in your terminal to test its functionality:
streamlit hello
You can see streamlit Hello world app in a new tab in your web browser.
Text Elements Examples
- Title: Defines the page’s title.
- Header: Showcases text using header formatting.
- Subheader: Presents text in sub header formatting.
- Markdown: Applies markdown formatting to the text.
- Code: Exhibits text as code with suitable syntax highlighting.
-
Latex: Utilizes LaTeX to present mathematical equations.
Create a file named
text_example.py
and add the following code to it.
import streamlit as st
# set the app's title
st.title("Title in Streamlit")
# header
st.header("Header in Streamlit")
# subheader
st.subheader("Subheader in Streamlit")
# markdown
# display text in bold formatting
st.markdown("**Streamlit** is a widely used open-source Python framework, facilitates the creation and deployment of web apps for Machine Learning and Data Science.")
# display text in italic formatting
st.markdown("Visit [Streamlit](https://docs.streamlit.io) to learn more about Streamlit.")
# code block
code = '''
def add(a, b):
print("a+b = ", a+b)
'''
st.code(code, language='python')
# latex
st.latex('''
(a+b)^2 = a^2 + b^2 + 2*a*b
''')
Run the text example using the following command.
streamlit run text_example.py
Widget Examples
Input
import streamlit as st
# text input
name = st.text_input("Enter your name", "")
st.write("Your name is ", name)
age = st.number_input(label="Enter your age")
st.write("Your age is ", age)
address = st.text_area("Enter your address", "")
st.write("Your address is ", address)
Button
import streamlit as st
#button
if st.button('Click me', help="Click to see the text change"):
st.write('Welcome to Streamlit!')
else:
st.write('Hi there!')
Checkbox
import streamlit as st
# check box
checked = st.checkbox('Click me')
if checked:
st.write('You agreed the terms and conditions!')
Radio
import streamlit as st
# radio button
lang = st.radio(
"What's your favorite programming language?",
('C','C++', 'Java','Python'))
if lang == 'C':
st.write('You selected C')
elif lang == 'C++':
st.write('You selected C++')
elif lang == 'C++':
st.write('You selected Java')
else:
st.write('You selected Python')
Slider
import streamlit as st
# slider
age = st.slider('Please enter your age',
min_value=0, max_value=100, value=10)
st.write("Your age is ", age)
Date and Time
import datetime
import streamlit as st
date = st.date_input("When's your birthday", datetime.date(2000, 1, 1), datetime.date(1990, 1, 1), datetime.datetime.now())
st.write("Your birthday is ", date)
time = st.time_input("Which is your birth time", datetime.time(0, 0))
st.write("Your birth time is ", time)
Form
import streamlit as st
with st.form("user_form"):
st.header("User Registration")
name = st.text_input("Enter your name", "")
age = st.slider("Enter your age")
gender = st.radio("Select your gender", ('Male', 'Female'))
terms = st.checkbox("Accept terms and conditions")
# Every form must have a submit button.
submitted = st.form_submit_button("Submit")
if submitted:
if terms:
st.write("Name: ", name, ", Age: ", age, ", Gender: ", gender)
else:
st.write("Accept terms and conditions")
st.write("Thanks for visiting")
Status
import streamlit as st
import time
# progress
progress_text = "Operation in progress. Please wait."
my_bar = st.progress(0, text=progress_text)
for percent_complete in range(100):
time.sleep(0.1)
my_bar.progress(percent_complete + 1, text=progress_text)
# spinner
with st.spinner('Wait for it...'):
time.sleep(5)
st.success('Done!')
# messages
st.toast('Your edited image was saved!', icon='😍')
st.error('This is an error', icon="🚨")
st.info('This is a purely informational message', icon="ℹ️")
st.warning('This is a warning', icon="⚠️")
st.success('This is a success message!', icon="✅")
e = RuntimeError('This is an exception of type RuntimeError')
st.exception(e)
Chart
import streamlit as st
import pandas as pd
import numpy as np
# chart
chart_data = pd.DataFrame(
np.random.randn(20, 3),
columns=['a', 'b', 'c'])
st.line_chart(chart_data)
st.bar_chart(chart_data)
st.area_chart(chart_data)
df = pd.DataFrame(
np.random.randn(1000, 2) / [50, 50] + [37.76, -122.4],
columns=['lat', 'lon'])
st.map(df)
Data
import streamlit as st
import pandas as pd
import numpy as np
# data frame
st.subheader("Data Frame")
df = pd.DataFrame(
np.random.randn(50, 20),
columns=('col %d' % i for i in range(20)))
st.dataframe(df) # Same as st.write(df)
# table
st.subheader("Data Table")
df = pd.DataFrame(
np.random.randn(10, 5),
columns=('col %d' % i for i in range(5)))
st.table(df)
# data editor
st.subheader("Data Editor")
df = pd.DataFrame(
[
{"command": "st.selectbox", "rating": 4, "is_widget": True},
{"command": "st.balloons", "rating": 5, "is_widget": False},
{"command": "st.time_input", "rating": 3, "is_widget": True},
]
)
st.data_editor(df)
# metric
st.subheader("Data Metric")
st.metric(label="Temperature", value="70 °F", delta="1.2 °F")
col1, col2, col3 = st.columns(3)
col1.metric("Temperature", "70 °F", "1.2 °F")
col2.metric("Wind", "9 mph", "-8%")
col3.metric("Humidity", "86%", "4%")
# json
st.subheader("Data JSON")
st.json({
'foo': 'bar',
'baz': 'boz',
'stuff': [
'stuff 1',
'stuff 2',
'stuff 3',
'stuff 5',
],
})
Chat
import streamlit as st
import numpy as np
prompt = st.chat_input("Enter the chart type (bar, area, line)")
print(prompt)
if prompt == "bar":
with st.chat_message("user"):
st.write("Bar Chart Demo 👋")
st.bar_chart(np.random.randn(30, 3))
elif prompt == "area":
with st.chat_message("user"):
st.write("Area Chat Demo 👋")
st.area_chart(np.random.randn(30, 3))
elif prompt == "line":
with st.chat_message("user"):
st.write("Line Chat Demo 👋")
st.line_chart(np.random.randn(30, 3))
elif prompt is not None:
with st.chat_message("user"):
st.write("Wrong chart type")
Thanks for reading this article.
Thanks Gowri M Bhatt for reviewing the content.
If you enjoyed this article, please click on the heart button ♥ and share to help others find it!
The full source code for this tutorial can be found here,
GitHub - codemaker2015/streamlit-cheatsheet | github.com
The article is also available on Medium.
Here are some useful links,
Top comments (0)