Streamlit: The Python Tool for Data Application Development
Hello everyone! Today I want to introduce a Python library that excites me – Streamlit. I still remember when I first developed data visualization applications, I was either troubled by front-end development or hindered by complex web frameworks. Until I met Streamlit, it was like a magical wand that allowed me to create beautiful web applications with just a few lines of Python code. Whether it’s data display, machine learning model deployment, or interactive data analysis, Streamlit helps us easily accomplish it. Let’s explore this powerful tool together!
Basic Interface Elements
Let’s start with the most basic interface elements:
import streamlit as st
import pandas as pd
import numpy as np
# Set the page title
st.title('My First Streamlit App')
# Add text
st.text('This is plain text')
st.markdown('**This is Markdown text**')
st.write('This is a general display function')
# Display data
df = pd.DataFrame({
'Name': ['Zhang San', 'Li Si', 'Wang Wu'],
'Age': [25, 30, 35],
'City': ['Beijing', 'Shanghai', 'Guangzhou']
})
st.dataframe(df) # Display table
st.table(df) # Display static table
Tip:
st.write()
is a versatile display function that can automatically determine the data type and choose the appropriate display method!
Input Controls
Streamlit provides a rich set of input controls:
# Text input
name = st.text_input('Please enter your name', 'Guest')
st.write(f'Hello, {name}!')
# Number input
age = st.number_input('Please enter age', min_value=0, max_value=120, value=25)
# Slider
score = st.slider('Please select a score', 0, 100, 60)
# Select box
option = st.selectbox(
'Choose your favorite programming language',
['Python', 'Java', 'JavaScript', 'Go']
)
# Multi-select
options = st.multiselect(
'Select your skills',
['Python', 'SQL', 'Machine Learning', 'Deep Learning'],
['Python']
)
# Checkbox
if st.checkbox('Show more information'):
st.write('Here is more information...')
Data Visualization
Combine various visualization libraries to display beautiful charts:
import plotly.express as px
import matplotlib.pyplot as plt
# Use Plotly to draw interactive charts
df = px.data.iris()
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species")
st.plotly_chart(fig)
# Use Matplotlib to draw charts
plt.figure(figsize=(10, 6))
plt.plot(np.random.randn(100))
st.pyplot(plt)
# Use Streamlit native charts
chart_data = pd.DataFrame(
np.random.randn(20, 3),
columns=['A', 'B', 'C']
)
st.line_chart(chart_data)
Layout Control
Use layout features to organize page content:
# Sidebar
with st.sidebar:
st.title('Control Panel')
user_input = st.text_input('Input parameters')
# Column display
col1, col2 = st.columns(2)
with col1:
st.header('First Column')
st.write('This is the content on the left')
with col2:
st.header('Second Column')
st.write('This is the content on the right')
# Expandable panel
with st.expander('Click to expand for more details'):
st.write('Here is the detailed content...')
st.image('https://example.com/image.jpg')
Status and Caching
Optimize application performance:
# Cache computation results
@st.cache_data
def load_big_data():
data = pd.read_csv('big_file.csv')
return data
# Show loading status
with st.spinner('Loading data...'):
data = load_big_data()
st.success('Loading complete!')
# Progress bar
progress_bar = st.progress(0)
for i in range(100):
progress_bar.progress(i + 1)
Practical Case: Data Analysis Dashboard
import streamlit as st
import pandas as pd
import plotly.express as px
def load_data():
# Assume this is our data
return pd.DataFrame(
np.random.randn(100, 3),
columns=['Sales', 'Profit', 'Cost']
)
def main():
st.title('Sales Data Analysis Dashboard')
# Sidebar filter
with st.sidebar:
st.header('Filter Criteria')
date_range = st.date_input(
'Select date range',
[pd.Timestamp('2025-01-01'), pd.Timestamp('2025-01-24')]
)
# Load data
df = load_data()
# Display key metrics
col1, col2, col3 = st.columns(3)
with col1:
st.metric('Total Sales', f'{df["Sales"].sum():.2f}')
with col2:
st.metric('Total Profit', f'{df["Profit"].sum():.2f}')
with col3:
st.metric('Total Cost', f'{df["Cost"].sum():.2f}')
# Chart display
tab1, tab2 = st.tabs(['Sales Trend', 'Distribution Analysis'])
with tab1:
fig1 = px.line(df, y=['Sales', 'Profit'], title='Sales and Profit Trends')
st.plotly_chart(fig1)
with tab2:
fig2 = px.histogram(df, x='Sales', title='Sales Distribution')
st.plotly_chart(fig2)
# View raw data
if st.checkbox('Show raw data'):
st.dataframe(df)
if __name__ == '__main__':
main()
Summary
Today we learned the core features of Streamlit:
-
Basic interface elements -
Using input controls -
Data visualization -
Layout control -
Status and caching management
Key reminders:
-
Use st.cache_data
to optimize performance -
Use layout features appropriately -
Pay attention to data update mechanisms -
Keep the interface simple and intuitive
Learning suggestions:
Start with simple data displays Try different interactive controls Focus on user experience Gradually add features
Practice problems:
-
Create a personal blog system -
Develop a stock data analysis tool -
Create a machine learning model demonstration application -
Implement a data visualization dashboard
Streamlit is like our all-in-one development assistant, making data application development so simple and enjoyable. Remember, a good application should not only be powerful but also focus on user experience. Next time, we will delve into more advanced features of Streamlit. Now, start your journey in data application development!