Streamlit: A Super Library for Data Visualization

Streamlit: A Super Library for Data Visualization

Hello everyone! Today I want to introduce you to an amazing data visualization library – Streamlit. Are you still struggling to create data display interfaces? Streamlit is like giving you a “data magic wand”; with just a few lines of Python code, you can create professional data visualization web pages! You don’t need to know front-end development, no need to write HTML and CSS, everything is done with Python. I was simply amazed the first time I used it; let’s explore this magical tool together!

What is Streamlit?

I like to compare Streamlit to “Transformers of the data display world.” Just like Transformers can easily change into various forms, Streamlit allows your data to be displayed in various cool ways. Plus, it’s super simple to use; if you can write Python, you can get started right away!

First, let’s install Streamlit:

pip install streamlit

Quick Start: Basic Components

1. Text and Title Display

import streamlit as st

# Add title and text
st.title("My First Streamlit App")
st.header("This is a Title")
st.subheader("This is a Sub-title")
st.text("This is regular text")
st.markdown("**This is Markdown text**")

# Display colored text
st.success("This is a success message")
st.info("This is an info message")
st.warning("This is a warning message")
st.error("This is an error message")

Tip: To run the Streamlit app, just type in the command line: streamlit run app.py

2. Data Display Components

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'],
    'Age': [25, 30, 35],
    'City': ['Beijing', 'Shanghai', 'Guangzhou']
})

# Display data
st.dataframe(data)  # Interactive data table
st.table(data)      # Static table
st.json({           # JSON data
    "name": "Zhang San",
    "age": 25
})

Advanced Features

1. Chart Drawing

import streamlit as st
import pandas as pd
import plotly.express as px

# Create sample data
df = pd.DataFrame({
    'Date': pd.date_range('2023-01-01', '2023-12-31', freq='M'),
    'Sales': np.random.randn(12).cumsum()
})

# Draw chart
st.line_chart(df.set_index('Date'))  # Line chart

# Use Plotly to draw more complex charts
fig = px.line(df, x='Date', y='Sales', title='Monthly Sales Trend')
st.plotly_chart(fig)

2. Interactive Components

import streamlit as st

# Input components
name = st.text_input("Please enter your name")
age = st.slider("Please select your age", 0, 100, 25)
city = st.selectbox("Please select your city", ["Beijing", "Shanghai", "Guangzhou"])

# Button and checkbox
if st.button("Submit"):
    st.write(f"Hello, {name}!")
    st.write(f"You are {age} years old")
    st.write(f"You live in {city}")

show_data = st.checkbox("Show raw data")
if show_data:
    st.dataframe(df)

Real Application Scenarios

1. Data Analysis Dashboard

import streamlit as st
import pandas as pd
import plotly.express as px

def load_data():
    # Load data (example with random data)
    df = pd.DataFrame({
        'Date': pd.date_range('2023-01-01', '2023-12-31', freq='D'),
        'Sales': np.random.randn(365).cumsum(),
        'Category': np.random.choice(['A', 'B', 'C'], 365)
    })
    return df

def main():
    st.title("Sales Data Analysis Dashboard")
    
    # Sidebar filters
    st.sidebar.header("Filter Options")
    category = st.sidebar.multiselect(
        "Select Category",
        ["A", "B", "C"],
        default=["A", "B", "C"]
    )
    
    # Load data
    df = load_data()
    filtered_df = df[df['Category'].isin(category)]
    
    # Display statistics
    col1, col2, col3 = st.columns(3)
    with col1:
        st.metric("Total Sales", f"{filtered_df['Sales'].sum():.0f}")
    with col2:
        st.metric("Average Sales", f"{filtered_df['Sales'].mean():.2f}")
    with col3:
        st.metric("Sales Days", len(filtered_df))
    
    # Draw chart
    fig = px.line(filtered_df, x='Date', y='Sales', color='Category')
    st.plotly_chart(fig)

if __name__ == "__main__":
    main()

2. File Upload and Processing

import streamlit as st
import pandas as pd

def process_file():
    st.title("File Processor")
    
    # File upload
    uploaded_file = st.file_uploader("Select CSV file", type=['csv'])
    
    if uploaded_file is not None:
        # Read data
        df = pd.read_csv(uploaded_file)
        
        # Display basic information about data
        st.write("Data Preview:")
        st.dataframe(df.head())
        
        st.write("Data Statistics:")
        st.write(df.describe())
        
        # Download processed data
        if st.button("Download Processed Data"):
            processed_data = df.to_csv(index=False)
            st.download_button(
                "Click to Download",
                processed_data,
                "processed_data.csv",
                "text/csv"
            )

if __name__ == "__main__":
    process_file()

Practical Tips

1. Page Layout Optimization

import streamlit as st

# Use column layout
col1, col2 = st.columns(2)
with col1:
    st.header("Left Content")
    st.write("This is the content on the left side")
    
with col2:
    st.header("Right Content")
    st.write("This is the content on the right side")

# Use container
with st.container():
    st.write("This is a container")
    
# Use expander
with st.expander("Click to Expand"):
    st.write("This is the expanded content")

Exercise

Try this practical task:

  1. Support CSV file upload
  2. Display basic statistics
  3. Draw common charts
  4. Add interactive filters

Reference code framework:

import streamlit as st
import pandas as pd
import plotly.express as px

def data_explorer():
    st.title("Data Exploration Tool")
    
    # TODO: Implement file upload
    
    # TODO: Add data analysis functionality
    
    # TODO: Implement visualization part

if __name__ == "__main__":
    data_explorer()

Summary

Streamlit is truly an amazing data visualization tool! Its main advantages include:

  • Easy to use, all written in Python
  • Rich components, powerful functionality
  • Real-time refresh, efficient development
  • Easy deployment, easy sharing
  • Beautiful and professional display

I suggest everyone start practicing with simple displays and gradually add more interactive features. Remember:

  1. Use layout components wisely
  2. Pay attention to performance optimization
  3. Keep the interface clean and clear

If you want to quickly create data display interfaces, you must try Streamlit! It can make your data display work both simple and professional.

Let’s make data display more interesting together! If you have any questions, feel free to discuss them in the comments!

Streamlit: A Super Library for Data Visualization

Leave a Comment