Python中一個(gè)構(gòu)建 web 頁面的神奇庫 streamlit

背景

在上一篇文章《基于DeepSeek,構(gòu)建個(gè)人本地RAG知識(shí)庫》中用到了 streamlit 庫,于是小編初步深入了解了一下,感覺很好用,是數(shù)據(jù)人的一個(gè)好幫手,避免學(xué)習(xí)前端知識(shí),利用該庫直接在 Python 中編碼代碼,然后啟動(dòng)服務(wù)后,在瀏覽器中可以直接查看 web 頁面,省略了后端、前端構(gòu)建 web 的繁瑣過程,數(shù)據(jù)人可以直接把自己的數(shù)據(jù)以 web 形式展示出來

小編環(huán)境

import sys
print('python 版本:',sys.version)
#python 版本: 3.11.11 | packaged by Anaconda, Inc. | 
#(main, Dec 11 2024, 16:34:19) [MSC v.1929 64 bit (AMD64)]

import streamlit
print(streamlit.__version__)
#1.42.2

import pandas as pd 
print(pd.__version__)
#2.2.2

import numpy as np 
print(np.__version__)
#2.2.2

import matplotlib
print(matplotlib.__version__)
#3.10.0

streamlit 庫使用

1. 安裝

和安裝其他三方包一樣,進(jìn)行安裝 streamlit

pip install streamlit

2. 使用

  • 導(dǎo)入需要的庫
import streamlit as st 
import pandas as pd 
import numpy as np 
import matplotlib.pyplot as plt
  • 各種文本
    header:一級(jí)標(biāo)題
    subheader:二級(jí)標(biāo)題
    text:純文本
    markdown:支持markdown語法
    code:代碼
# 展示一級(jí)標(biāo)題
st.header('2. 使用')

# 展示二級(jí)標(biāo)題
st.subheader('2.1 生成 Markdown 文檔')

# 純文本
st.text("""導(dǎo)入 streamlit 后,就可以直接使用 st.markdown() 初始化,
該方法支持 markdown 語法""")

# markdown
st.markdown('markdown用法:**加粗**,*傾斜* \n - 1 \n- 2 ')

# 展示代碼,有高亮效果
code2 = '''import streamlit as st
st.markdown('Streamlit 初步學(xué)習(xí)')'''
st.code(code2, language='python')

web頁面效果:


效果
  • 表格
    table:普通表格
    dataframe:高級(jí)表格,可以進(jìn)行數(shù)據(jù)的操作,比如排序
# 展示一級(jí)標(biāo)題
st.header('3. 圖表')

# markdown
st.markdown('關(guān)于數(shù)據(jù)的展示,streamlit 由兩個(gè)組件進(jìn)行支持')
st.markdown('- table:普通的表格,用于靜態(tài)數(shù)據(jù)的展示')
st.markdown('- dataframe:高級(jí)的表格,可以進(jìn)行數(shù)據(jù)的操作,比如排序')

# 展示二級(jí)標(biāo)題
st.subheader('3.1 Table 的示例')

df = pd.DataFrame(
    np.random.randn(10, 5),
    columns=('第%d列' % (i+1) for i in range(5))
)

st.table(df)


# 展示二級(jí)標(biāo)題
st.subheader('3.2 DataFrame 的示例')
st.dataframe(df.style.highlight_max(axis=0))

web頁面效果:


效果
  • 監(jiān)控組件
    可以使用 st.columns 先生成3列,然后針對(duì)每列調(diào)用 metric 方法,生成監(jiān)控組件
# 展示一級(jí)標(biāo)題
st.header('4. 監(jiān)控組件')
# markdown
st.markdown('streamlit 也為你提供的 metric 組件')

col1, col2, col3 = st.columns(3)
col1.metric("溫度", "70 °F", "1.2 °F")
col2.metric("風(fēng)速", "9 mph", "-8%")
col3.metric("濕度", "86%", "4%")

web頁面效果:


效果
  • 內(nèi)部原生圖表
    Streamlit 原生支持多種圖表:
    st.line_chart:折線圖
    st.area_chart:面積圖
    st.bar_chart:柱狀圖
    st.map:地圖
# 展示一級(jí)標(biāo)題
st.header('5. 原生圖表組件')

# markdown
st.markdown('Streamlit 原生支持多種圖表:')
st.markdown('- st.line_chart:折線圖')
st.markdown('- st.area_chart:面積圖')
st.markdown('- st.bar_chart:柱狀圖')
st.markdown('- st.map:地圖')


# 展示二級(jí)標(biāo)題
st.subheader('5.1 折線圖')
chart_data = pd.DataFrame(
    np.random.randn(20, 3),
    columns=['a', 'b', 'c'])

st.line_chart(chart_data)


# 展示二級(jí)標(biāo)題
st.subheader('5.2 面積圖')
chart_data = pd.DataFrame(
    np.random.randn(20, 3),
    columns = ['a', 'b', 'c'])

st.area_chart(chart_data)
st.area_chart(chart_data,x_label='x',y_label='y',stack='center')
st.area_chart(chart_data,x_label='x',y_label='y',stack=True)
st.area_chart(chart_data,x_label='x',y_label='y',stack=False)


# 展示二級(jí)標(biāo)題
st.subheader('5.3 柱狀圖')

chart_data = pd.DataFrame(
    np.random.randn(5, 3),
    columns = ["a", "b", "c"])
st.bar_chart(chart_data)
st.bar_chart(chart_data,stack=False)
st.bar_chart(chart_data,stack=False,horizontal=True)



# 展示二級(jí)標(biāo)題
st.subheader('5.3 地圖')
df = pd.DataFrame(
    np.random.randn(1000, 2) / [50, 50] + [39.91, 116.41],
    columns=['lat', 'lon']
)
st.map(df)

web頁面效果:


折線圖

柱狀圖

地圖
  • 集成三方庫圖表*
    Streamlit 除了一些原生圖表組件,同時(shí)還支持像 matplotlib.pyplot、Altair、vega-lite、Plotly、Bokeh、PyDeck、Graphviz 等的外部圖表,這里演示一下 matplotlib.pyplot 的用法
# 展示一級(jí)標(biāo)題
st.header('6. 外部圖表組件')

st.markdown("""
    Streamlit 的一些原生圖表組件,雖然做到了傻瓜式,但僅能輸入數(shù)據(jù)、高度和寬度,
    如果你想更漂亮的圖表,就像 
    matplotlib.pyplot、Altair、vega-lite、Plotly、Bokeh、PyDeck、Graphviz 
    那樣,streamlit 也提供了支持:
    
    - st.pyplot
    - st.bokeh_chart
    - st.altair_chart
    - st.altair_chart
    - st.vega_lite_chart
    - st.plotly_chart
    - st.pydeck_chart
    - st.graphviz_chart
    """
    )

# 展示二級(jí)標(biāo)題
st.subheader('6.1 matplotlib.pyplot')

arr = np.random.normal(1, 1, size=100)
print(arr)
fig, ax = plt.subplots()
ax.hist(arr, bins=20)
st.pyplot(fig)

web頁面效果:


外部圖表

歷史相關(guān)文章


以上是自己實(shí)踐中遇到的一些問題,分享出來供大家參考學(xué)習(xí),歡迎關(guān)注微信公眾號(hào):DataShare ,不定期分享干貨

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容