feature: new
This commit is contained in:
234
app.py
Normal file
234
app.py
Normal file
@@ -0,0 +1,234 @@
|
||||
"""
|
||||
Streamlit 示例应用
|
||||
一个展示 Streamlit 各种功能的示例应用
|
||||
"""
|
||||
|
||||
import streamlit as st
|
||||
import pandas as pd
|
||||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
import plotly.express as px
|
||||
from datetime import datetime
|
||||
|
||||
# 页面配置
|
||||
st.set_page_config(
|
||||
page_title="Streamlit 示例应用",
|
||||
page_icon="🎈",
|
||||
layout="wide",
|
||||
initial_sidebar_state="expanded",
|
||||
)
|
||||
|
||||
# 应用标题
|
||||
st.title("🎈 Streamlit 示例应用")
|
||||
st.markdown("这是一个展示 Streamlit 各种功能的示例应用。")
|
||||
|
||||
# 侧边栏
|
||||
with st.sidebar:
|
||||
st.header("⚙️ 配置选项")
|
||||
|
||||
# 主题选择
|
||||
theme = st.selectbox("选择主题", ["浅色", "深色", "自动"], help="选择应用的主题")
|
||||
|
||||
# 示例数据点数量
|
||||
data_points = st.slider(
|
||||
"数据点数量",
|
||||
min_value=10,
|
||||
max_value=1000,
|
||||
value=100,
|
||||
step=10,
|
||||
help="调整生成示例数据的数据点数量",
|
||||
)
|
||||
|
||||
# 颜色选择
|
||||
color = st.color_picker("选择图表颜色", "#1f77b4")
|
||||
|
||||
st.divider()
|
||||
st.caption("这是一个示例应用的侧边栏,可以放置各种配置选项。")
|
||||
|
||||
# 创建标签页
|
||||
tab1, tab2, tab3, tab4 = st.tabs(
|
||||
["📊 图表展示", "📁 数据操作", "📝 表单输入", "ℹ️ 关于"]
|
||||
)
|
||||
|
||||
with tab1:
|
||||
st.header("📊 图表展示")
|
||||
|
||||
# 生成示例数据
|
||||
np.random.seed(42)
|
||||
x = np.linspace(0, 10, data_points)
|
||||
y = np.sin(x) + np.random.normal(0, 0.1, data_points)
|
||||
df = pd.DataFrame({"x": x, "y": y})
|
||||
|
||||
col1, col2 = st.columns(2)
|
||||
|
||||
with col1:
|
||||
st.subheader("折线图 (Matplotlib)")
|
||||
fig, ax = plt.subplots()
|
||||
ax.plot(df["x"], df["y"], color=color, linewidth=2)
|
||||
ax.set_xlabel("X 轴")
|
||||
ax.set_ylabel("Y 轴")
|
||||
ax.set_title("正弦波示例")
|
||||
ax.grid(True, alpha=0.3)
|
||||
st.pyplot(fig)
|
||||
|
||||
with col2:
|
||||
st.subheader("散点图 (Plotly)")
|
||||
fig = px.scatter(
|
||||
df,
|
||||
x="x",
|
||||
y="y",
|
||||
title="散点图示例",
|
||||
labels={"x": "X 轴", "y": "Y 轴"},
|
||||
color_discrete_sequence=[color],
|
||||
)
|
||||
fig.update_traces(marker=dict(size=8, opacity=0.6))
|
||||
st.plotly_chart(fig, use_container_width=True)
|
||||
|
||||
# 柱状图
|
||||
st.subheader("柱状图示例")
|
||||
categories = ["A", "B", "C", "D", "E"]
|
||||
values = np.random.randint(10, 100, len(categories))
|
||||
bar_df = pd.DataFrame({"类别": categories, "数值": values})
|
||||
|
||||
fig = px.bar(
|
||||
bar_df,
|
||||
x="类别",
|
||||
y="数值",
|
||||
title="柱状图",
|
||||
color="数值",
|
||||
color_continuous_scale="Viridis",
|
||||
)
|
||||
st.plotly_chart(fig, use_container_width=True)
|
||||
|
||||
with tab2:
|
||||
st.header("📁 数据操作")
|
||||
|
||||
# 生成示例数据表
|
||||
st.subheader("示例数据表")
|
||||
sample_data = pd.DataFrame(
|
||||
{
|
||||
"日期": pd.date_range("2023-01-01", periods=10),
|
||||
"销售额": np.random.randint(1000, 5000, 10),
|
||||
"利润": np.random.randint(100, 1000, 10),
|
||||
"地区": np.random.choice(["北京", "上海", "广州", "深圳"], 10),
|
||||
}
|
||||
)
|
||||
|
||||
st.dataframe(sample_data, use_container_width=True)
|
||||
|
||||
# 数据统计
|
||||
st.subheader("数据统计")
|
||||
col1, col2, col3 = st.columns(3)
|
||||
with col1:
|
||||
st.metric("总销售额", f"¥{sample_data['销售额'].sum():,}")
|
||||
with col2:
|
||||
st.metric("平均利润", f"¥{sample_data['利润'].mean():.0f}")
|
||||
with col3:
|
||||
st.metric("地区数量", sample_data["地区"].nunique())
|
||||
|
||||
# 文件上传示例
|
||||
st.subheader("文件上传")
|
||||
uploaded_file = st.file_uploader(
|
||||
"上传 CSV 文件", type=["csv"], help="上传一个 CSV 文件进行数据展示"
|
||||
)
|
||||
|
||||
if uploaded_file is not None:
|
||||
try:
|
||||
uploaded_df = pd.read_csv(uploaded_file)
|
||||
st.write("上传的数据预览:")
|
||||
st.dataframe(uploaded_df.head(), use_container_width=True)
|
||||
except Exception as e:
|
||||
st.error(f"文件读取错误: {e}")
|
||||
|
||||
with tab3:
|
||||
st.header("📝 表单输入")
|
||||
|
||||
# 表单示例
|
||||
with st.form("示例表单"):
|
||||
st.subheader("用户信息")
|
||||
|
||||
col1, col2 = st.columns(2)
|
||||
with col1:
|
||||
name = st.text_input("姓名", placeholder="请输入您的姓名")
|
||||
email = st.text_input("邮箱", placeholder="example@email.com")
|
||||
|
||||
with col2:
|
||||
age = st.number_input("年龄", min_value=0, max_value=150, value=25)
|
||||
country = st.selectbox(
|
||||
"国家/地区", ["中国", "美国", "英国", "日本", "其他"]
|
||||
)
|
||||
|
||||
interests = st.multiselect(
|
||||
"兴趣",
|
||||
["编程", "数据科学", "机器学习", "Web开发", "设计", "其他"],
|
||||
["编程", "数据科学"],
|
||||
)
|
||||
|
||||
bio = st.text_area("个人简介", placeholder="简单介绍一下自己...", height=100)
|
||||
|
||||
agree = st.checkbox("我同意服务条款")
|
||||
|
||||
submitted = st.form_submit_button("提交")
|
||||
|
||||
if submitted:
|
||||
if not agree:
|
||||
st.error("请同意服务条款")
|
||||
elif not name:
|
||||
st.error("请输入姓名")
|
||||
else:
|
||||
st.success("表单提交成功!")
|
||||
st.json(
|
||||
{
|
||||
"姓名": name,
|
||||
"邮箱": email,
|
||||
"年龄": age,
|
||||
"国家/地区": country,
|
||||
"兴趣": interests,
|
||||
"个人简介": bio[:50] + "..." if len(bio) > 50 else bio,
|
||||
}
|
||||
)
|
||||
|
||||
with tab4:
|
||||
st.header("ℹ️ 关于")
|
||||
|
||||
st.markdown("""
|
||||
## Streamlit 示例应用
|
||||
|
||||
### 功能特性
|
||||
|
||||
- 📊 **图表展示**: 使用 Matplotlib 和 Plotly 创建各种图表
|
||||
- 📁 **数据操作**: 数据表展示、统计指标、文件上传
|
||||
- 📝 **表单输入**: 用户信息收集表单
|
||||
- ⚙️ **侧边栏配置**: 主题、数据点数量等配置选项
|
||||
|
||||
### 技术栈
|
||||
|
||||
- **Streamlit**: 用于构建数据应用的 Python 框架
|
||||
- **Pandas**: 数据处理和分析
|
||||
- **NumPy**: 数值计算
|
||||
- **Matplotlib**: 静态图表绘制
|
||||
- **Plotly**: 交互式图表绘制
|
||||
|
||||
### 使用说明
|
||||
|
||||
1. 在侧边栏调整配置选项
|
||||
2. 浏览不同标签页查看各种功能
|
||||
3. 尝试表单提交和数据上传
|
||||
|
||||
### 运行命令
|
||||
|
||||
```bash
|
||||
# 使用 just 运行
|
||||
just run
|
||||
|
||||
# 或直接使用 uv
|
||||
uv run streamlit run app.py
|
||||
```
|
||||
""")
|
||||
|
||||
st.divider()
|
||||
st.caption(f"最后更新: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
|
||||
|
||||
# 页脚
|
||||
st.divider()
|
||||
st.caption("🎈 这是一个 Streamlit 示例应用 | 使用 Streamlit 构建")
|
||||
Reference in New Issue
Block a user