Hello everyone, I am Liang Ge. Today, I will take you into a very interesting and powerful Python library—Streamlit. It helps developers quickly build and deploy data visualization applications, making complex analytical results simple and understandable. Next, I will explain the charm of Streamlit in detail through six parts: background introduction, installation guide, basic usage, advanced usage, practical case studies, and summary.
Background Introduction
In today’s digital age, the importance of data is self-evident. However, how to present complex data in an intuitive and understandable way to users has always been a challenge for developers. Traditional data visualization tools often require complex code and cumbersome configurations, while the emergence of Streamlit is like a breath of fresh air, making data visualization accessible in a simple and efficient way. Streamlit is an open-source Python library designed specifically for data scientists and machine learning engineers, capable of quickly converting Python scripts into interactive web applications, greatly improving development efficiency and user experience.
Installation Guide
Before we start using Streamlit, we need to install and configure it. Installing Streamlit is very simple, just run the following command in the terminal:
pip install streamlit
After installation, we also need to ensure that other necessary libraries, such as Pandas and Matplotlib, are installed in the Python environment, as these libraries are often used with Streamlit. If not installed, you can do so with the following command:
pip install pandas matplotlib
In addition, to better run Streamlit applications, it is recommended to use a virtual environment to manage project dependencies, which can avoid dependency conflicts between different projects.
Basic Usage
Once the installation is complete, we can start using Streamlit. Creating a simple Streamlit application is very intuitive. First, create a Python file, such as app.py
, and then write the following code in the file:
import streamlit as st
import pandas as pd
# Set the page title
st.title("My First Streamlit App")
# Create a simple data table
data = pd.DataFrame({
"Name": ["Zhang San", "Li Si", "Wang Wu"],
"Age": [25, 30, 35],
"Occupation": ["Engineer", "Designer", "Product Manager"]
})
# Display the data table
st.write("This is a simple data table:")
st.write(data)
After saving the file, run the following command in the terminal:
streamlit run app.py
At this point, Streamlit will automatically start a local server and open the application in the browser. You will see a title and a simple data table displayed on the page, which is the basic usage of Streamlit. By using functions like st.title()
and st.write()
, we can easily display text and data on the page.
Advanced Usage
After mastering the basic usage, we can further explore the advanced features of Streamlit. Streamlit provides rich components and interactive features, such as buttons, sliders, dropdown menus, etc., which can help users interact with the application. Here is an example code that includes interactive features:
import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt
# Set the page title
st.title("Data Visualization Application")
# Create a simple data table
data = pd.DataFrame({
"Name": ["Zhang San", "Li Si", "Wang Wu"],
"Age": [25, 30, 35],
"Occupation": ["Engineer", "Designer", "Product Manager"]
})
# Display the data table
st.write("This is a simple data table:")
st.write(data)
# Add a slider to select age range
age_range = st.slider("Select Age Range", min_value=20, max_value=40, value=(25, 35))
# Filter data based on slider value
filtered_data = data[(data["Age"] >= age_range[0]) & (data["Age"] <= age_range[1])]
# Display filtered data
st.write("Filtered Data:")
st.write(filtered_data)
# Add a button to generate a chart
if st.button("Generate Chart"):
# Create a bar chart
fig, ax = plt.subplots()
ax.bar(filtered_data["Name"], filtered_data["Age"])
ax.set_xlabel("Name")
ax.set_ylabel("Age")
ax.set_title("Age Bar Chart")
st.pyplot(fig)
In this example, we added a slider and a button. Users can select an age range through the slider and then click the button to generate the corresponding bar chart. This interactivity makes the application more flexible and user-friendly.
Practical Case Studies
To better understand the practical value of Streamlit, let’s look at a specific case. Suppose we are data analysts at an e-commerce company and need to create a sales data visualization application for the management team. We can quickly build an interactive dashboard through Streamlit to display sales data for different time periods and regions. Here is a simplified code example:
import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt
# Load sales data
sales_data = pd.read_csv("sales_data.csv")
# Set the page title
st.title("Sales Data Visualization Dashboard")
# Add a dropdown menu to select region
region = st.selectbox("Select Region", sales_data["Region"].unique())
# Filter data based on selected region
filtered_data = sales_data[sales_data["Region"] == region]
# Display sales data statistics
st.write("Sales Data Statistics:")
st.write(filtered_data.describe())
# Add a slider to select time range
time_range = st.slider("Select Time Range", min_value=filtered_data["Date"].min(), max_value=filtered_data["Date"].max(), value=(filtered_data["Date"].min(), filtered_data["Date"].max()))
# Filter data based on time range
filtered_data = filtered_data[(filtered_data["Date"] >= time_range[0]) & (filtered_data["Date"] <= time_range[1])]
# Display filtered sales data
st.write("Filtered Sales Data:")
st.write(filtered_data)
# Add a button to generate sales trend chart
if st.button("Generate Sales Trend Chart"):
# Create a line chart
fig, ax = plt.subplots()
ax.plot(filtered_data["Date"], filtered_data["Sales Amount"])
ax.set_xlabel("Date")
ax.set_ylabel("Sales Amount")
ax.set_title("Sales Trend Chart")
st.pyplot(fig)
In this case, we used Streamlit’s dropdown menu, slider, and button components to achieve interactive querying and visualization of sales data. The management team can quickly understand sales conditions in different regions and time periods through simple operations, enabling them to make more informed decisions.
Summary
From the above introduction, we can see that Streamlit is a very powerful and easy-to-use Python library. It not only allows for the rapid construction of data visualization applications but also provides rich interactive features, enabling developers to implement complex functionalities in a simple way. Whether you are a data scientist, machine learning engineer, or an ordinary data enthusiast, Streamlit is a tool worth trying. I hope this article can help you better understand and use Streamlit, making data visualization simpler and more enjoyable.