Hello everyone! Today I want to share with you an amazing Python library – Streamlit. Are you still struggling to build data visualization web pages? In the past, you might have needed to master various technologies like HTML, CSS, and JavaScript, but with Streamlit, all you need is to write Python code! It’s like a magic wand that can turn your data into a beautiful web application with just a few lines of code. Trust me, using it to showcase your data analysis results will definitely impress your leaders and colleagues!
Installing Streamlit
First, let’s install Streamlit using pip:
pip install streamlit
Your First Application
1. Hello Streamlit
Let’s start with the simplest example:
import streamlit as st
# Set the page title
st.title("My First Streamlit App")
# Add text
st.write("Hello, Streamlit!")
# Add a slider
age = st.slider("What is your age?", 0, 100, 25)
st.write(f"Your age is: {age} years")
Save it as app.py, and then run it in the terminal:
streamlit run app.py
Tip: Streamlit will automatically open the browser to display the app, and the page will refresh automatically every time you save the code!
2. Data Display
import streamlit as st
import pandas as pd
import numpy as np
# Create sample data
data = pd.DataFrame({
'Name': ['Zhang San', 'Li Si', 'Wang Wu', 'Zhao Liu'],
'Age': [25, 30, 35, 40],
'City': ['Beijing', 'Shanghai', 'Guangzhou', 'Shenzhen']
})
# Display data table
st.table(data)
# Display interactive dataframe
st.dataframe(data)
Visualization Components
1. Chart Display
import streamlit as st
import pandas as pd
import plotly.express as px
# Create sample data
df = pd.DataFrame(
np.random.randn(20, 3),
columns=['Stock A', 'Stock B', 'Stock C']
)
# Line chart
st.line_chart(df)
# Area chart
st.area_chart(df)
# Bar chart
st.bar_chart(df)
# Plotly chart
fig = px.scatter(df, x='Stock A', y='Stock B', title='Stock Comparison')
st.plotly_chart(fig)
2. Interactive Components
import streamlit as st
# Select box
option = st.selectbox(
'Choose your favorite programming language',
['Python', 'JavaScript', 'Java', 'Go']
)
# Multi-select box
options = st.multiselect(
'Select the frameworks you are familiar with',
['Flask', 'Django', 'FastAPI', 'Streamlit']
)
# Button
if st.button('Click me'):
st.write('Button was clicked!')
# Text input
name = st.text_input('Enter your name')
if name:
st.write(f'Hello, {name}!')
Layout Design
1. Sidebar
import streamlit as st
# Sidebar
with st.sidebar:
st.title("Control Panel")
user_name = st.text_input("Username")
user_age = st.slider("Age", 0, 100, 25)
is_member = st.checkbox("Is a member")
# Main page content
st.write(f"Username: {user_name}")
st.write(f"Age: {user_age}")
st.write(f"Membership status: {'Yes' if is_member else 'No'}")
2. Column Layout
import streamlit as st
col1, col2, col3 = st.columns(3)
with col1:
st.header("First Column")
st.write("This is the content of the first column")
with col2:
st.header("Second Column")
st.write("This is the content of the second column")
with col3:
st.header("Third Column")
st.write("This is the content of the third column")
Real Application Cases
1. Stock Data Display
import streamlit as st
import yfinance as yf
import plotly.graph_objects as go
def show_stock_price():
st.title('Stock Data Viewer')
# Input stock code
stock_code = st.text_input('Enter stock code (e.g., AAPL)')
if stock_code:
# Get stock data
data = yf.download(stock_code, start='2020-01-01')
# Display candlestick chart
fig = go.Figure(data=[go.Candlestick(
x=data.index,
open=data['Open'],
high=data['High'],
low=data['Low'],
close=data['Close']
)])
st.plotly_chart(fig)
2. Data Analysis Dashboard
import streamlit as st
import pandas as pd
import plotly.express as px
def create_dashboard():
st.title('Sales Data Analysis Dashboard')
# Upload data file
uploaded_file = st.file_uploader("Select CSV file", type=['csv'])
if uploaded_file:
df = pd.read_csv(uploaded_file)
# Display basic statistics
st.subheader('Data Overview')
st.write(df.describe())
# Plot sales trend
st.subheader('Sales Trend')
fig = px.line(df, x='date', y='sales')
st.plotly_chart(fig)
# Display regional distribution
st.subheader('Regional Distribution')
fig = px.pie(df, values='sales', names='region')
st.plotly_chart(fig)
Deploying Applications
1. Running Locally
streamlit run app.py
2. Cloud Deployment
# requirements.txt
streamlit==1.24.0
pandas==1.5.3
plotly==5.15.0
Small Exercises
Try these exercises:
-
Create a personal resume display page -
Create a data visualization dashboard -
Develop a simple machine learning model display application -
Create a file upload and processing tool
Notes
-
Pay attention to the real-time nature of data; you can use st.cache to optimize performance -
Use layout wisely to make the page clearer -
Add appropriate interactive features to enhance user experience -
Be mindful of code modularity and reusability
Frequently Asked Questions
Q: How to make the application faster?
A: Use the @st.cache decorator to cache data processing results.
Q: How to change the page theme?
A: You can use st.set_page_config to set the theme and layout.
Q: How to share data between different pages?
A: Use st.session_state to store session data.
That’s all for today’s sharing! Streamlit is truly an irresistible tool that makes data visualization so easy. The best part is that you don’t need to understand front-end development to create professional data applications.
Remember, good visualization not only displays data but also tells the story behind the data. Quickly use Streamlit to create your first data application! If you create something interesting, feel free to share it in the comments. See you next time!