Streamlit使用方法
安装
# 安装Streamlit
pip install streamlit
# 根据需要安装 matplotlib等
依赖
aiohttp==3.8.4
aiosignal==1.3.1
altair==4.2.2
async-timeout==4.0.2
attrs==22.2.0
blinker==1.5
cachetools==5.3.0
charset-normalizer==3.1.0
click==8.1.3
colorama==0.4.6
contourpy==1.0.7
cycler==0.11.0
decorator==5.1.1
entrypoints==0.4
fonttools==4.39.2
frozenlist==1.3.3
gitdb==4.0.10
GitPython==3.1.31
idna==3.4
importlib-metadata==6.1.0
Jinja2==3.1.2
jsonschema==4.17.3
kiwisolver==1.4.4
markdown-it-py==2.2.0
MarkupSafe==2.1.2
matplotlib==3.7.1
mdurl==0.1.2
multidict==6.0.4
numpy==1.24.2
openai==0.27.2
packaging==23.0
pandas==1.5.3
Pillow==9.4.0
plotly==5.13.1
protobuf==3.20.3
pyarrow==11.0.0
pydeck==0.8.0
Pygments==2.14.0
Pympler==1.0.1
pyparsing==3.0.9
pyrsistent==0.19.3
python-dateutil==2.8.2
pytz==2022.7.1
pytz-deprecation-shim==0.1.0.post0
requests==2.28.2
rich==13.3.2
scipy==1.10.1
seaborn==0.12.2
semver==2.13.0
six==1.16.0
smmap==5.0.0
streamlit==1.20.0
streamlit-chat==0.0.2.2
tenacity==8.2.2
toml==0.10.2
toolz==0.12.0
tornado==6.2
tqdm==4.65.0
typing_extensions==4.5.0
tzdata==2023.2
tzlocal==4.3
urllib3==1.26.15
validators==0.20.0
watchdog==3.0.0
wincertstore==0.2
yarl==1.8.2
zipp==3.15.0
使用
import streamlit as st
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import base64
import seaborn as sns
import plotly.figure_factory as ff
import altair as alt
import scipy
import time
# doc
# <https://docs.streamlit.io/library/api-reference/text/st.header>
# st.set_option('deprecation.showPyplotGlobalUse', False)
st.title("st.title")
st.header("st.header")
st.subheader("st.subheader")
# ------------------------------------
# 展示文本;文本直接使用Markdown语法
st.markdown("# Streamlit示例")
st.markdown("""
- 这是
- 一个
- 无序列表
""")
st.markdown("# markdown一级标题")
st.markdown("## markdown二级标题")
st.markdown("### markdown三级标题")
st.markdown("***markdown粗斜体***")
st.markdown("markdown普通文字")
# ------------------------------------
# 展示pandas数据框
st.dataframe(pd.DataFrame([[1, 2], [3, 4]], columns=["a", "b"]))
# 展示matplotlib绘图
arr = np.random.normal(1, 1, size=100)
plt.hist(arr, bins=20)
plt.title("matplotlib plot")
st.pyplot()
# ------------------------------------
st.latex("\\\\sum_{i=1}^{n}")
# ------------------------------------
# st.write用法
st.write("st.write")
st.text("st.text")
st.write(1234)
st.write("1234")
st.write("1 + 1 = ", 2)
# write(data_frame) : Displays the DataFrame as a table.
# write(func) : Displays information about a function.
# write(module) : Displays information about the module.
# write(dict) : Displays dict in an interactive widget.
# write(obj) : The default is to print str(obj).
# write(mpl_fig) : Displays a Matplotlib figure.
# write(altair) : Displays an Altair chart.
# write(keras) : Displays a Keras model.
# write(graphviz) : Displays a Graphviz graph.
# write(plotly_fig) : Displays a Plotly figure.
# write(bokeh_fig) : Displays a Bokeh figure.
# write(sympy_expr) : Prints SymPy expression using LaTeX.
# write(markdown):
# ------------------------------------
# 各种控件
# 数字输入框
number = st.number_input("Insert a number", 123)
# 单行文本输入框
word = st.text_input("Insert a word", "123")
st.write("The number is", number, "The word is", word)
# 多行文本输入框
st.text_area("Text to analyze", "I love China")
# 日期输入框
st.date_input("Insert a date")
# 时间输入框
st.time_input("Insert a time")
# 点击按钮
number = st.button("click it")
st.write("返回值:", number)
# 滑动条
x = st.slider("Square", min_value=0, max_value=80)
st.write(x, "squared is", np.power(x, 2))
# 检查框
res = st.checkbox("I agree")
st.write(res)
# 单选框
st.selectbox("Which would you like", [1, 2, 3])
# 单选按钮
st.radio("Which would you like", [1, 2, 3])
# 多选框
selector = st.multiselect("Which would you like", [1, 2, 3])
st.write(selector)
# 气球效果
st.balloons()
# ------------------------------------
# 上传
uploaded_file = st.file_uploader("Choose a CSV file", type="csv")
if uploaded_file is not None:
data = pd.read_csv(uploaded_file)
st.write(data)
# 下载
data = [(1, 2, 3)]
df = pd.DataFrame(data, columns=["Col1", "Col2", "Col3"])
csv = df.to_csv(index=False)
b64 = base64.b64encode(csv.encode()).decode()
href = f'<a href="data:file/csv;base64,{b64}">Download CSV File</a> (right-click and save as <some_name>.csv)'
st.markdown(href, unsafe_allow_html=True)
# ------------------------------------
# 侧边栏
# 单选框
st.sidebar.selectbox("Which would you like", [1, 2, 3], key="1")
# 单选按钮
st.sidebar.radio("Which would you like", [1, 2, 3], key="2")
# 多选框
selector = st.sidebar.multiselect("Which would you like", [1, 2, 3], key="3")
st.write(selector)
# ------------------------------------
# 绘图、图片、音频、视频
# streamlit 自带绘图:st.line_chart()、bar_chart() 等
# matplotlib 或 seaborn:st.pyplot()
# altair:st.altair_chart()
# vega: st.vega_lite_chart()
# plotly: st.plotly_chart()
# bokeh: st.bokeh_chart()
st.line_chart(np.random.randn(10, 2))
chart_data = pd.DataFrame(
np.random.randn(50, 3),
columns=["a", "b", "c"]
)
st.bar_chart(chart_data)
# matplotlib 或 seaborn 绘图
st.markdown("# matplotlib绘图")
arr = np.random.normal(1, 1, size=100)
plt.hist(arr, bins=20)
st.pyplot()
st.markdown("# seaborn绘图")
tips = sns.load_dataset("tips")
sns.set(style="darkgrid")
sns.scatterplot(x="total_bill", y="tip", hue="smoker", data=tips)
st.pyplot()
# plotly 绘图
x1 = np.random.randn(200) - 2
x2 = np.random.randn(200)
x3 = np.random.randn(200) + 2
hist_data = [x1, x2, x3]
group_labels = ["Group 1", "Group 2", "Group 3"]
fig = ff.create_distplot(
hist_data, group_labels,
bin_size=[0.1, 0.25, 0.5])
st.markdown("# plotly绘图")
st.plotly_chart(fig)
# 地图# 绘制1000个点的坐标
map_data = pd.DataFrame(
np.random.randn(1000, 2) / [50, 50] + [37.76, -122.4],
columns=['lat', 'lon'])
st.map(map_data)
# 展示图片、音频、视频
# 图片:st.image ()
# 音频:st.audio ()
# 视频:st.video ()
st.error("错误显示为")
st.warning("警告显示为")
st.info("普通消息显示为")
st.success("成功消息显示为")
# 展示进度
# 添加两个占位符
slot1 = st.empty()
slot2 = st.empty()
# 占位符中插入文字
time.sleep(0.5)
slot1.markdown("# This will appear")
# 占位符中画图
time.sleep(0.5)
slot2.line_chart(np.random.randn(20, 2))
# 进度条
# 添加占位符
placeholder = st.empty()
# 创建进度条
bar = st.progress(0)
for i in range(100):
time.sleep(0.05)
# 不断更新占位符的内容
placeholder.text(f"Iteration {i+1}")
# 不断更新进度条
bar.progress(i + 1)
# 状态
st.success("Finished")
# 等待条
with st.spinner("Wait for it..."):
for i in range(100):
print("hello")
time.sleep(0.05)
st.success("Done!")
# 动态扩增表格
df1 = pd.DataFrame(
np.random.randn(5, 5),
columns=("col %d" % i for i in range(5))
)
tb_table = st.table(df1)
for i in range(10):
df2 = pd.DataFrame(
np.random.randn(1, 5),
columns=("col %d" % i for i in range(5))
)
tb_table.add_rows(df2)
time.sleep(0.5)
# 动态折线图
pb = st.progress(0)
status_txt = st.empty()
chart = st.line_chart(np.random.randn(10, 2))
for i in range(100):
pb.progress(i)
new_rows = np.random.randn(10, 2)
status_txt.text(
"The latest number is: %s" % new_rows[-1, 1]
)
chart.add_rows(new_rows)
time.sleep(0.05)
# 缓存
# 对于费时间的步骤,可打包成函数,并使用缓存;第一次调用函数时,正常运行过程;第二次调用函数时,则不再重新计算,而是直接使用上一步调用函数时返回的结果。
@st.cache() # 使用缓存
def compute_long_time():
SUM = 0
for i in range(100):
SUM += i
time.sleep(0.05)
return SUM
# 第一次调用函数,费时较长
st.write(compute_long_time())
# 再次调用该函数,瞬间出结果
st.write(compute_long_time())
# Magic commands
# Streamlit 提供了魔法方法,对于某些内容,直接书写便会自动调用 st.write ()
"***hello world***"
"""
# This is the document title
This is some _markdown_.
"""
# ---------------------------------
st.write("***hello world***")
st.write("""
# This is the document title
This is some _markdown_.
""")
# ---------------------------------
st.markdown("***hello world***")
st.markdown("""
# This is the document title
This is some _markdown_.
""")
# 可以看到,以上三种书写展示结果相同,原因为第一种方式会自动调用 st.write()(魔法方法),
# 而 st.write() 为一个泛型函数,内部传入 Markdown 时会自动调用 st.markdown(),
# 因此三种方式归根结底都是使用了 st.markdown()
# 展示 df 和 x,两者效果相同
df = pd.DataFrame({"col1": [1, 2, 3]})
df
x = 10
"x", x
# ---------------------------------
df = pd.DataFrame({"col1": [1, 2, 3]})
st.write(df) # 默认调用st.dataframe()
x = 10
st.write("x", x)
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# doc
# <https://docs.streamlit.io/library/api-reference/text/st.header>
# st.set_option('deprecation.showPyplotGlobalUse', False)
st.title("st.title")
st.header("st.header")
st.subheader("st.subheader")
# ------------------------------------
# 展示文本;文本直接使用Markdown语法
st.markdown("# Streamlit示例")
st.markdown("""
- 这是
- 一个
- 无序列表
""")
st.markdown("# markdown一级标题")
st.markdown("## markdown二级标题")
st.markdown("### markdown三级标题")
st.markdown("***markdown粗斜体***")
st.markdown("markdown普通文字")
# ------------------------------------
# 展示pandas数据框
st.dataframe(pd.DataFrame([[1, 2], [3, 4]], columns=["a", "b"]))
# 展示matplotlib绘图
arr = np.random.normal(1, 1, size=100)
plt.hist(arr, bins=20)
plt.title("matplotlib plot")
st.pyplot()
# ------------------------------------
st.latex("\\\\sum_{i=1}^{n}")
# ------------------------------------
# st.write用法
st.write("st.write")
st.text("st.text")
st.write(1234)
st.write("1234")
st.write("1 + 1 = ", 2)
# write(data_frame) : Displays the DataFrame as a table.
# write(func) : Displays information about a function.
# write(module) : Displays information about the module.
# write(dict) : Displays dict in an interactive widget.
# write(obj) : The default is to print str(obj).
# write(mpl_fig) : Displays a Matplotlib figure.
# write(altair) : Displays an Altair chart.
# write(keras) : Displays a Keras model.
# write(graphviz) : Displays a Graphviz graph.
# write(plotly_fig) : Displays a Plotly figure.
# write(bokeh_fig) : Displays a Bokeh figure.
# write(sympy_expr) : Prints SymPy expression using LaTeX.
# write(markdown):
# ------------------------------------
# 各种控件
# 数字输入框
number = st.number_input("Insert a number", 123)
# 单行文本输入框
word = st.text_input("Insert a word", "123")
st.write("The number is", number, "The word is", word)
# 多行文本输入框
st.text_area("Text to analyze", "I love China")
# 日期输入框
st.date_input("Insert a date")
# 时间输入框
st.time_input("Insert a time")
# 点击按钮
number = st.button("click it")
st.write("返回值:", number)
# 滑动条
x = st.slider("Square", min_value=0, max_value=80)
st.write(x, "squared is", np.power(x, 2))
# 检查框
res = st.checkbox("I agree")
st.write(res)
# 单选框
st.selectbox("Which would you like", [1, 2, 3])
# 单选按钮
st.radio("Which would you like", [1, 2, 3])
# 多选框
selector = st.multiselect("Which would you like", [1, 2, 3])
st.write(selector)
# 气球效果
st.balloons()
# ------------------------------------
# 上传
uploaded_file = st.file_uploader("Choose a CSV file", type="csv")
if uploaded_file is not None:
data = pd.read_csv(uploaded_file)
st.write(data)
# 下载
data = [(1, 2, 3)]
df = pd.DataFrame(data, columns=["Col1", "Col2", "Col3"])
csv = df.to_csv(index=False)
b64 = base64.b64encode(csv.encode()).decode()
href = f'<a href="data:file/csv;base64,{b64}">Download CSV File</a> (right-click and save as <some_name>.csv)'
st.markdown(href, unsafe_allow_html=True)
# ------------------------------------
# 侧边栏
# 单选框
st.sidebar.selectbox("Which would you like", [1, 2, 3], key="1")
# 单选按钮
st.sidebar.radio("Which would you like", [1, 2, 3], key="1")
# 多选框
selector = st.sidebar.multiselect("Which would you like", [1, 2, 3], key="3")
st.write(selector)
# ------------------------------------
# 绘图、图片、音频、视频
# streamlit 自带绘图:st.line_chart()、bar_chart() 等
# matplotlib 或 seaborn:st.pyplot()
# altair:st.altair_chart()
# vega: st.vega_lite_chart()
# plotly: st.plotly_chart()
# bokeh: st.bokeh_chart()
st.line_chart(np.random.randn(10, 2))
chart_data = pd.DataFrame(
np.random.randn(50, 3),
columns=["a", "b", "c"]
)
st.bar_chart(chart_data)
# matplotlib 或 seaborn 绘图
st.markdown("# matplotlib绘图")
arr = np.random.normal(1, 1, size=100)
plt.hist(arr, bins=20)
st.pyplot()
st.markdown("# seaborn绘图")
tips = sns.load_dataset("tips")
sns.set(style="darkgrid")
sns.scatterplot(x="total_bill", y="tip", hue="smoker", data=tips)
st.pyplot()
# plotly 绘图
x1 = np.random.randn(200) - 2
x2 = np.random.randn(200)
x3 = np.random.randn(200) + 2
hist_data = [x1, x2, x3]
group_labels = ["Group 1", "Group 2", "Group 3"]
fig = ff.create_distplot(
hist_data, group_labels,
bin_size=[0.1, 0.25, 0.5])
st.markdown("# plotly绘图")
st.plotly_chart(fig)
# 地图# 绘制1000个点的坐标
map_data = pd.DataFrame(
np.random.randn(1000, 2) / [50, 50] + [37.76, -122.4],
columns=['lat', 'lon'])
st.map(map_data)
# 展示图片、音频、视频
# 图片:st.image ()
# 音频:st.audio ()
# 视频:st.video ()
st.error("错误显示为")
st.warning("警告显示为")
st.info("普通消息显示为")
st.success("成功消息显示为")
# 展示进度
# 添加两个占位符
slot1 = st.empty()
slot2 = st.empty()
# 占位符中插入文字
time.sleep(0.5)
slot1.markdown("# This will appear")
# 占位符中画图
time.sleep(0.5)
slot2.line_chart(np.random.randn(20, 2))
# 进度条
# 添加占位符
placeholder = st.empty()
# 创建进度条
bar = st.progress(0)
for i in range(100):
time.sleep(0.05)
# 不断更新占位符的内容
placeholder.text(f"Iteration {i+1}")
# 不断更新进度条
bar.progress(i + 1)
# 状态
st.success("Finished")
# 等待条
with st.spinner("Wait for it..."):
for i in range(100):
print("hello")
time.sleep(0.05)
st.success("Done!")
# 动态扩增表格
df1 = pd.DataFrame(
np.random.randn(5, 5),
columns=("col %d" % i for i in range(5))
)
tb_table = st.table(df1)
for i in range(10):
df2 = pd.DataFrame(
np.random.randn(1, 5),
columns=("col %d" % i for i in range(5))
)
tb_table.add_rows(df2)
time.sleep(0.5)
# 动态折线图
pb = st.progress(0)
status_txt = st.empty()
chart = st.line_chart(np.random.randn(10, 2))
for i in range(100):
pb.progress(i)
new_rows = np.random.randn(10, 2)
status_txt.text(
"The latest number is: %s" % new_rows[-1, 1]
)
chart.add_rows(new_rows)
time.sleep(0.05)
# 缓存
# 对于费时间的步骤,可打包成函数,并使用缓存;第一次调用函数时,正常运行过程;第二次调用函数时,则不再重新计算,而是直接使用上一步调用函数时返回的结果。
@st.cache() # 使用缓存
def compute_long_time():
SUM = 0
for i in range(100):
SUM += i
time.sleep(0.05)
return SUM
# 第一次调用函数,费时较长
st.write(compute_long_time())
# 再次调用该函数,瞬间出结果
st.write(compute_long_time())
# Magic commands
# Streamlit 提供了魔法方法,对于某些内容,直接书写便会自动调用 st.write ()
"***hello world***"
"""
# This is the document title
This is some _markdown_.
"""
# ---------------------------------
st.write("***hello world***")
st.write("""
# This is the document title
This is some _markdown_.
""")
# ---------------------------------
st.markdown("***hello world***")
st.markdown("""
# This is the document title
This is some _markdown_.
""")
# 可以看到,以上三种书写展示结果相同,原因为第一种方式会自动调用 st.write()(魔法方法),
# 而 st.write() 为一个泛型函数,内部传入 Markdown 时会自动调用 st.markdown(),
# 因此三种方式归根结底都是使用了 st.markdown()
# 展示 df 和 x,两者效果相同
df = pd.DataFrame({"col1": [1, 2, 3]})
df
x = 10
"x", x
# ---------------------------------
df = pd.DataFrame({"col1": [1, 2, 3]})
st.write(df) # 默认调用st.dataframe()
x = 10
st.write("x", x)
评论区