Streamlit: A Magical Data Visualization Python Library!

Hello everyone, I am Cat Brother! Today I want to introduce you to a Python library that I am absolutely in love with – Streamlit. It allows us to create beautiful data visualization interfaces in just a few minutes! As a data analyst, I used to struggle with presenting data analysis results, but since I discovered Streamlit, everything has become so simple. With just a few lines of Python code, I can build a professional data dashboard, it’s just amazing!

Quick Start

First, install Streamlit: pip install streamlit. Let’s look at the simplest example:

import streamlit as st

st.title("My First Streamlit App")
st.write("Hello, World!")

# Add a slider
number = st.slider("Select a number", 0, 100)
st.write(f"The number you selected is: {number}")

Running it is very simple, save it as app.py and enter in the terminal: streamlit run app.py

Data Display Wizard

Streamlit’s support for data display is simply perfect!

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

# Create example data
df = pd.DataFrame({
    'Name': ['Zhang San', 'Li Si', 'Wang Wu', 'Zhao Liu'],
    'Age': [25, 30, 35, 40],
    'Income': [8000, 12000, 15000, 20000]
})

# Display data table
st.subheader("Employee Information Table")
st.dataframe(df)

# Display statistical chart
st.subheader("Income Distribution")
st.bar_chart(df['Income'])

Collection of Interactive Components

1. Basic Input Components

import streamlit as st

# Text input
name = st.text_input("Please enter your name")

# Number input
age = st.number_input("Please enter your age", min_value=0, max_value=120)

# Dropdown select box
option = st.selectbox(
    "What is your favorite programming language?",
    ["Python", "JavaScript", "Java", "Go"]
)

# Multi-select box
languages = st.multiselect(
    "Which programming languages do you know?",
    ["Python", "JavaScript", "Java", "Go"]
)

# Display results
if name:
    st.write(f"Hello, {name}!")
    st.write(f"You are {age} years old")
    st.write(f"Your favorite language is: {option}")
    st.write(f"Languages you know: {', '.join(languages)}")

2. Chart Drawing

import streamlit as st
import plotly.express as px
import numpy as np

# Generate example data
np.random.seed(42)
data = np.random.normal(0, 1, 1000)

# Use plotly to draw a histogram
fig = px.histogram(data, title="Normal Distribution Example")
st.plotly_chart(fig)

# Add interactive controls
bins = st.slider("Set the number of bins for the histogram", 10, 100, 50)
fig = px.histogram(data, nbins=bins, title=f"Normal Distribution ({bins} bins)")
st.plotly_chart(fig)

Practical Project: Stock Data Analyzer

import streamlit as st
import yfinance as yf
import pandas as pd
import plotly.graph_objs as go

st.title("πŸ“ˆ Stock Data Analyzer")

# Stock code input
stock_code = st.text_input("Please enter the stock code (e.g., AAPL)", "AAPL")

# Date range selection
col1, col2 = st.columns(2)
with col1:
    start_date = st.date_input("Start Date")
with col2:
    end_date = st.date_input("End Date")

if st.button("Get Data"):
    # Get stock data
    @st.cache_data  # Use caching to speed up
    def load_data():
        data = yf.download(stock_code, start=start_date, end=end_date)
        return data
    
data = load_data()
    
    # Display stock information
    st.subheader("Stock Data Overview")
    st.dataframe(data.head())
    
    # Draw candlestick chart
    fig = go.Figure(data=[go.Candlestick(x=data.index,
                open=data['Open'],
                high=data['High'],
                low=data['Low'],
                close=data['Close'])])
    
    fig.update_layout(title=f"{stock_code} Stock Candlestick Chart")
    st.plotly_chart(fig)
    
    # Calculate simple technical indicators
    data['MA5'] = data['Close'].rolling(window=5).mean()
    data['MA20'] = data['Close'].rolling(window=20).mean()
    
    # Draw moving average chart
    st.subheader("Moving Average Analysis")
    fig = go.Figure()
    fig.add_trace(go.Scatter(x=data.index, y=data['Close'], name="Close Price"))
    fig.add_trace(go.Scatter(x=data.index, y=data['MA5'], name="5-Day Moving Average"))
    fig.add_trace(go.Scatter(x=data.index, y=data['MA20'], name="20-Day Moving Average"))
    st.plotly_chart(fig)

Tips:

  • Using st.cache_data can cache data and improve application performance
  • Streamlit supports markdown syntax to beautify text display
  • You can use st.columns to create multi-column layouts

Practice Assignments

  1. Create a simple weather forecast application
  2. Create a personal expense statistics analyzer
  3. Develop a COVID-19 data visualization dashboard

Advanced Tips:

  • Try using st.sidebar to add a sidebar
  • Explore st.session_state for state management
  • Learn to use st.file_uploader to handle file uploads

Friends, today’s Python learning journey ends here! Streamlit is truly a magical tool for data visualization, allowing us to quickly build professional data applications. Remember to get hands-on coding, and feel free to ask Cat Brother in the comments if you have any questions. Let’s use Streamlit to create cool data applications together! I wish everyone happy learning, and may your Python skills improve steadily!

Leave a Comment