Create Data Visualization Web Apps in 10 Minutes with Streamlit

Have You Encountered the Following Issues?

  • Need to create a webpage for data analysis results but lack frontend development skills?
  • Graphs created with Matplotlib require too many adjustments to display?
  • Flask + Vue configuration and deployment are too complex?
  • Don’t know how to create a real-time interactive dashboard?

See How Easy It Is to Use Streamlit

import streamlit as st
import pandas as pd

# Load data
df = pd.read_csv('sales.csv')

# Add title and chart
st.title('Sales Data Dashboard')
st.line_chart(df['sales'])

# Add interactive filter
year = st.selectbox('Select Year', df['year'].unique())
filtered_data = df[df['year'] == year]

πŸ’‘ Tip: No frontend knowledge required, just one command to start: streamlit run app.py

Practical: Build a Data Dashboard from Scratch

Using Basic Components

import streamlit as st
import pandas as pd
import numpy as np

# Page configuration
st.set_page_config(page_title="Data Dashboard", layout="wide")

# Add title
st.title('Sales Data Analysis')
st.markdown('### Real-time Data Monitoring')

# Display data table
df = pd.DataFrame({
    'date': pd.date_range('2024-01-01', periods=10),
    'sales': np.random.randn(10).cumsum()
})
st.dataframe(df, use_container_width=True)

Interactive Charts

import plotly.express as px

# Create interactive chart
@st.cache_data  # Cache data loading
def load_data():
    return pd.read_csv('data.csv')

data = load_data()

# Add filters
col1, col2 = st.columns(2)
with col1:
    category = st.multiselect('Select Category', data['category'].unique())
with col2:
    date_range = st.date_input('Select Date Range')

# Draw chart
fig = px.line(data, x='date', y='value', color='category')
st.plotly_chart(fig, use_container_width=True)

Showcase of Advanced Features

Custom Component Layout

def create_dashboard():
    # Use column layout
    metrics_col, chart_col = st.columns([1, 2])
    
    with metrics_col:
        st.metric(
            label="Total Sales", 
            value="Β₯123,456",
            delta="12.3%"
        )
        st.metric(
            label="Number of Orders", 
            value="1,234",
            delta="-2.3%",
            delta_color="inverse"
        )
    
    with chart_col:
        st.area_chart(np.random.randn(20, 3))

if __name__ == "__main__":
    create_dashboard()

Performance Optimization Tips

# Use caching to reduce data loading
@st.cache_data(ttl=3600)  # Expires in one hour
def load_large_dataset():
    df = pd.read_csv('large_file.csv')
    return df.groupby('category').sum()

# Use session_state to save state
if 'data' not in st.session_state:
    st.session_state.data = load_large_dataset()

Useful Tips

1. File Upload and Processing

def process_file():
    uploaded_file = st.file_uploader("Select CSV File")
    if uploaded_file is not None:
        df = pd.read_csv(uploaded_file)
        st.success('File uploaded successfully!')
        return df
    return None

2. Real-time Data Updates

def real_time_monitor():
    placeholder = st.empty()
    while True:
        with placeholder.container():
            st.metric("Real-time Data", np.random.randint(100))
            time.sleep(1)

Frequently Asked Questions

Q: Does Streamlit support multi-page applications?

A: Yes! Just create multiple .py files in the pages folder, and it will automatically generate a sidebar navigation.

Q: How to deploy a Streamlit application?

A: You can deploy for free using Streamlit Cloud, or deploy to any server using Docker.

Q: Will it lag with large data sets?

A: Using the @st.cache_data decorator to cache data can significantly improve performance.

Q: Does it support user authentication?

A: You can use st.secrets to manage keys, along with st.session_state to implement a simple authentication system.

πŸš€ Want to quickly set up a beautiful data visualization application?

  1. pip install streamlit plotly pandas numpy
  2. Create app.py
  3. Run streamlit run app.py

It’s that simple, your data visualization site is live!

Interested friends can go practice.

Leave a Comment