1 說明:
=====
1.1 是一個開源Python庫,可輕松構建用于機器學習的漂亮應用程序。
1.2 我的第一篇文章,對其介紹、安裝、初步相關使用做了詳細的介紹:
《Streamlit是python的一個機器學習、數據科學、應用開發框架》
1.3 糾正末尾gif的st.slider圖:是下面的。
2 數據可視化作圖:
==============
2.1 Streamlit當前支持許多用于繪圖的庫,其中就有Plotly, Bokeh, Matplotlib, Altair和Vega圖表。
2.2 plotly法:
2.2.1 代碼:
import streamlit as st
st.title("數據可視化作圖")
st.header("折線圖")
#導入plotly并作圖
import plotly.graph_objs as go
trace0 = go.Scatter(x=[1, 2, 3, 4], y=[10, 15, 13, 17])
trace1 = go.Scatter(x=[1, 2, 3, 4], y=[16, 5, 11, 9])
data = [trace0, trace1]
#寫入數據并顯示圖
st.write(data) #用st.write
2.2.2 效果圖:
2.2.3 代碼:3D
import streamlit as st
import plotly.graph_objs as go
import numpy as np
#顯示標題
st.header("3D plot")
#隨機生成散點坐標軸
x, y, z = np.random.multivariate_normal(np.array([0, 0, 0]), np.eye(3), 400).transpose()
trace1 = go.Scatter3d(
x=x,
y=y,
z=z,
mode="markers",
marker=dict(
size=12,
color=z, # set color to an array/list of desired values
colorscale="Viridis", # choose a colorscale
opacity=0.8,
),
)
data = [trace1]
layout = go.Layout(margin=dict(l=0, r=0, b=0, t=0))
fig = go.Figure(data=data, layout=layout)
st.write(fig)
#streamlit run 6-plotly-3D.py
2.2.4 操作效果圖:
2.3 matplotlib法
2.3.1 代碼:
import streamlit as st
st.title("數據可視化作圖")
st.header("matplotlib-Scatter")
import matplotlib.pyplot as plt
f = plt.figure()
#附加學習Python的列表及列表推導式
x=[x for x in range(9)]
x1=x[1:]
#x1=[1,2,3,4,5,6,7,8] #等于上面2個
y=[3,6,2,7,4,8,5,3]
plt.scatter(x1,y)
#st.plotly_chart(f) #老版matplotlib的格式
st.write(f) #新版matplotlib
2.3.2 操作和效果圖:
2.4 altair法
2.4.1 代碼:
import streamlit as st
import altair as alt
from vega_datasets import data
source = data.cars()
#設置刷子,交互性
brush = alt.selection(type='interval')
points = alt.Chart().mark_point().encode(
x='Horsepower:Q', y='Miles_per_Gallon:Q',
color=alt.condition(brush, 'Origin:N', alt.value('lightgray')) ).add_selection( brush )
bars = alt.Chart().mark_bar().encode(
y='Origin:N', color='Origin:N', x='count(Origin):Q' ).transform_filter( brush )
#把點圖和柱狀圖掛在一起
bbb=alt.vconcat(points, bars, data=source)
#一起啟動服務器
#bbb.serve('0.0.0.0', 8888) #用altair啟動服務器自動瀏覽器打開
st.write(bbb) #streamlit run 7-altair.py #用終端啟動文件,沒有上面有優勢
2.4.2 操作效果圖:
3 st.file_uploader和st.button
======================
3.1 代碼:
import streamlit as st
import pandas as pd
uploaded_file = st.file_uploader("Choose a CSV file", type="csv")
if uploaded_file is not None:
data = pd.read_csv(uploaded_file)
if st.button('Say hello'):
st.write('Why hello there')
else:
st.write('Goodbye')
3.2 圖