Streamlit: Quickly Build Data Visualization Web Pages from Scratch

# Streamlit: Quickly Build Data Visualization Web Pages from Scratch
Hello everyone, I am Lao Wang. Today I want to introduce you to a super powerful Python library - Streamlit. It is like a magical wand that allows us to quickly create beautiful web applications with simple Python code. You don't need to know HTML, CSS, or JavaScript; as long as you can write Python, you can easily create professional-level data visualization pages. I often use it to showcase data analysis results, and the effect is simply amazing!

First, let’s install Streamlit and create our first application:

# Install Streamlit
pip install streamlit
# Run the application
streamlit run app.py

Create your first application (app.py):

import streamlit as st
# Set the page title
st.title('My First Streamlit Application')
# Add text
st.write('Hello, World!')
# Add sidebar
st.sidebar.write('This is the sidebar')
# Display data
import pandas as pd
df = pd.DataFrame({    'Name': ['Zhang San', 'Li Si', 'Wang Wu'],    'Age': [25, 30, 35]})
st.dataframe(df)

Data Visualization

Streamlit has very friendly support for various charts:

import streamlit as st
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Generate sample data
data = pd.DataFrame({    'Date': pd.date_range('2025-01-01', periods=100),    'Sales': np.random.randn(100).cumsum()})
# Line chart
st.line_chart(data.set_index('Date'))
# Bar chart
st.bar_chart(data.set_index('Date'))
# Matplotlib chart
fig, ax = plt.subplots()
ax.plot(data['Date'], data['Sales'])
st.pyplot(fig)

Interactive Components

Add various interactive controls:

import streamlit as st
# Text input
name = st.text_input('Please enter your name')
st.write(f'Hello, {name}!')
# Slider
age = st.slider('Select your age', 0, 100, 25)
st.write(f'You selected age: {age} years')
# Multi-select
options = st.multiselect(    'Programming languages you like',    ['Python', 'Java', 'JavaScript', 'C++'],    ['Python'])
# Button
if st.button('Click me'):    st.balloons()
# File upload
uploaded_file = st.file_uploader('Choose a CSV file')
if uploaded_file is not None:    data = pd.read_csv(uploaded_file)    st.write(data)

Page Layout

Flexible layout options:

import streamlit as st
# Column layout
col1, col2 = st.columns(2)
with col1:    st.write('This is the left side')
with col2:    st.write('This is the right side')
# Expander
with st.expander('Click to expand'):    st.write('Here are the details')
# Tabs
tab1, tab2 = st.tabs(['Data', 'Charts'])
with tab1:    st.write('This is the data tab')
with tab2:    st.write('This is the charts tab')

Practical Case: Data Analysis Dashboard

Let’s create a simple data analysis dashboard:

import streamlit as st
import pandas as pd
import plotly.express as px
# Page configuration
st.set_page_config(page_title='Sales Data Analysis', layout='wide')
def load_data():    # Replace with your data loading logic    return pd.DataFrame({        'Product': ['A', 'B', 'C'] * 4,        'Sales': np.random.randint(100, 1000, 12),        'Month': ['January', 'February', 'March'] * 4    })
# Load data
data = load_data()
# Sidebar filter
st.sidebar.header('Filter Conditions')
product = st.sidebar.multiselect('Select Product', data['Product'].unique())
# Main page
st.title('Sales Data Analysis Dashboard')
# Data overview
col1, col2 = st.columns(2)
with col1:    st.metric('Total Sales', data['Sales'].sum())
with col2:    st.metric('Average Sales', int(data['Sales'].mean()))
# Chart display
fig = px.bar(data, x='Month', y='Sales', color='Product',             title='Monthly Sales Trend')
st.plotly_chart(fig, use_container_width=True)

Exercises

  1. Create a simple to-do list application
  2. Create a file format conversion tool
  3. Develop a data visualization display page

Deployment Tips

  1. Local Run:
streamlit run app.py --server.port 8501
  1. Docker Deployment:
FROM python:3.9-slim
COPY . /app
WORKDIR /app
RUN pip install -r requirements.txt
EXPOSE 8501
CMD streamlit run app.py

Tips:

  • Use st.cache to cache data loading functions
  • Use layout components wisely to enhance page aesthetics
  • Pay attention to handle exceptions for user inputs
  • Regularly save user data and state

Dear friends, today’s Python learning journey ends here! Streamlit is truly a tool that makes data presentation super easy, so go ahead and try it to showcase your data analysis results! Feel free to ask me any questions in the comments section. Wishing everyone a happy learning experience and continuous improvement in Python!

#python #streamlit #data visualization #web application

Leave a Comment