Streamlit: A Powerful Tool for Rapid Data Application Development

Data analysts and developers are often troubled by a question: after the analysis is complete and the charts are drawn, how can these results be quickly shared with others? Sending Excel files? Sending PDFs? These methods feel too “cold”. Wouldn’t it be cooler to turn the data analysis results into an interactive web application? Streamlit, a Python library designed specifically for data applications, allows you to quickly build an interactive web application with just a few lines of code, running directly in the browser and supporting dynamic interactions.

Next, let’s take a look at how to use Streamlit.

1. Installation and Quick Experience

Installing Streamlit

Installing Streamlit is very simple, you can do it with pip:

pip install streamlit

After installation, run the following code to experience its charm.

A Quick Example

Create a new file named app.py and write the following code:

import streamlit as st

st.title("Streamlit First Experience")
st.write("This is a simple web application built with Streamlit.")

# Add interactive elements
name = st.text_input("Enter your name:")
st.write(f"Hello, {name}!")

After saving, open the terminal and run:

streamlit run app.py

At this point, the browser will automatically open a page, and your application is online! Doesn’t it feel like you’re just a few steps away from full-stack development?

2. Core Feature 1: Quickly Display Data

Streamlit helps you quickly display various types of data, such as text, charts, tables, etc., with simple and intuitive syntax.

Displaying Text

st.title("This is a Title")
st.header("This is a Level 2 Title")
st.subheader("This is a Level 3 Title")
st.write("This can display plain text or directly print variables.")

After running, you will see beautiful hierarchical titles and text content.

Displaying Tables

import pandas as pd

# Create a simple DataFrame
data = pd.DataFrame({
    "Column 1": [1, 2, 3],
    "Column 2": [4, 5, 6]
})

st.write("This is a table:")
st.dataframe(data)

st.dataframe will automatically render an interactive table, allowing users to scroll and sort, which is very convenient.

Displaying Charts

Streamlit supports integration with various visualization libraries, such as Matplotlib, Seaborn, Plotly, etc. You can also quickly draw charts using its built-in st.line_chart.

import numpy as np

# Generate random data
chart_data = pd.DataFrame(
    np.random.randn(20, 3),
    columns=["A", "B", "C"]
)

st.line_chart(chart_data)

This code will generate a dynamic line chart, and the data points can be freely adjusted.

3. Core Feature 2: Adding Interactive Components

Static data is already quite intuitive, but the real highlight of Streamlit lies in its interactivity. With various interactive components, you can involve users in data analysis.

Input Box

name = st.text_input("Please enter your name:")
st.write(f"Hello, {name}!")

After the user inputs content, the page will dynamically update to display the input result.

Checkbox

if st.checkbox("Show hidden content"):
    st.write("You checked the checkbox, this is some hidden content!")

After checking the checkbox, the hidden content will appear, which is very suitable for conditional display.

Dropdown Menu

option = st.selectbox(
    "Choose a fruit:",
    ["Apple", "Banana", "Orange"]
)
st.write(f"You selected: {option}")

Users can select an option from the dropdown menu, and the page will update in real-time.

4. Core Feature 3: File Upload and Download

Streamlit also supports file uploads and downloads, which is very practical.

Uploading Files

uploaded_file = st.file_uploader("Upload a file", type=["csv", "txt"])
if uploaded_file is not None:
    data = pd.read_csv(uploaded_file)
    st.write(data)

After the user uploads a file, the code will automatically read and display the file content.

Downloading Files

import io

# Create a CSV file
csv = data.to_csv(index=False)
st.download_button(
    label="Download Data",
    data=csv,
    file_name="data.csv",
    mime="text/csv"
)

After clicking the button, users can download the processed data to their local machine.

5. Core Feature 4: Layout and Columns

Streamlit supports simple layout controls, such as columns and collapsibles.

Columns

col1, col2 = st.columns(2)

with col1:
    st.write("This is the first column")

with col2:
    st.write("This is the second column")

The two columns will be displayed side by side, suitable for comparing data or displaying multiple charts simultaneously.

Collapsible

with st.expander("Click to expand content"):
    st.write("This is some hidden content.")

The collapsible component can make the page cleaner, allowing users to expand and view it when needed.

6. Core Feature 5: Real-time Updates and State Preservation

Streamlit natively supports real-time updates; every user interaction triggers a page refresh. However, sometimes we need to keep certain states unchanged, which can be done using st.session_state.

State Preservation

if "count" not in st.session_state:
    st.session_state.count = 0

if st.button("Increase Count"):
    st.session_state.count += 1

st.write(f"Current Count: {st.session_state.count}")

After clicking the button, the counter value will increase but will not be lost due to page refresh.

Real-time Updates

import time

st.write("Starting to load...")
my_bar = st.progress(0)

for percent in range(100):
    time.sleep(0.1)
    my_bar.progress(percent + 1)

st.write("Loading complete!")

This code will display a dynamic progress bar, showing a message after loading is complete.

7. Common Questions and Reminders

  1. Browser Not Opened If the browser does not open automatically after running streamlit run, manually visit http://localhost:8501.

  2. Real-time Updates Too Frequent Streamlit refreshes the page with every interaction; avoid writing complex loop logic, as it may lead to performance issues.

  3. File Upload Format Restrictions Ensure that the uploaded file format is correct, such as the type parameter of file_uploader.

8. More Possibilities with Streamlit

Streamlit can not only quickly build data analysis web applications but also supports integration with machine learning models, serving as an interactive platform for online predictions. If you are a data analyst or interested in data visualization, Streamlit is a tool worth trying. With it, you can turn your ideas into a cool application in just a few minutes!

Leave a Comment