在 Mac M1 上安裝與運行 Streamlit

STEP 1 : 安裝 Python 開發環境 (Conda)

可參考我的另一篇文章: 在ARM 版本的 Mac M1 上安裝 Python (Mini-forge Conda 虛擬環境)

STEP 2: 建置專案的虛擬環境

假設在~/Projects/Conda/envs/streamlit 的目錄下已新增一個專案名為 streamlit 的虛擬環境

  • % conda create -p ~/Projects/Conda/envs/streamlit python=3.9 -y

STEP 3: 啟動 (進入) streamlit 虛擬環境

  • % conda activate streamlit

進入專案的虛擬環境後, 可先檢查一下環境資訊與Python版本是否正確?

  • % conda info
  • % python -V

STEP 4: 安裝相關所需的套件

安裝套件 streamlit

  • % conda install -y streamlit

安裝套件 plotly

  • % conda install -y plotly

檢查版本

  • % streamlit version
顯示結果, 目前我的 Streamlit 版本為 version 1.0.0

STEP 5: 執行程式

  • % streamlit run 程式名稱.py

官方範例 hello

  • % streamlit hello

執行後, 瀏覽器會自動打開該網址, 或自行手動輸入亦可

## 進階範例

範例一:圖表

原始程式碼

import streamlit as st
import time
import numpy as np
progress_bar = st.sidebar.progress(0)
status_text = st.sidebar.empty()
last_rows = np.random.randn(1, 1)
chart = st.line_chart(last_rows)
for i in range(1, 101):
new_rows = last_rows[-1, :] + np.random.randn(5, 1).cumsum(axis=0)
status_text.text("%i%% Complete" % i)
chart.add_rows(new_rows)
progress_bar.progress(i)
last_rows = new_rows
time.sleep(0.05)
progress_bar.empty()# Streamlit widgets automatically run the script from top to bottom. Since
# this button is not connected to any other logic, it just causes a plain
# rerun.
st.button("Re-run")

範例二:動畫

原始程式碼

import streamlit as st
import numpy as np
# Interactive Streamlit elements, like these sliders, return their value.
# This gives you an extremely simple interaction model.
iterations = st.sidebar.slider("Level of detail", 2, 20, 10, 1)
separation = st.sidebar.slider("Separation", 0.7, 2.0, 0.7885)
# Non-interactive elements return a placeholder to their location
# in the app. Here we're storing progress_bar to update it later.
progress_bar = st.sidebar.progress(0)
# These two elements will be filled in later, so we create a placeholder
# for them using st.empty()
frame_text = st.sidebar.empty()
image = st.empty()
m, n, s = 960, 640, 400
x = np.linspace(-m / s, m / s, num=m).reshape((1, m))
y = np.linspace(-n / s, n / s, num=n).reshape((n, 1))
for frame_num, a in enumerate(np.linspace(0.0, 4 * np.pi, 100)):
# Here were setting value for these two elements.
progress_bar.progress(frame_num)
frame_text.text("Frame %i/100" % (frame_num + 1))
# Performing some fractal wizardry.
c = separation * np.exp(1j * a)
Z = np.tile(x, (n, 1)) + 1j * np.tile(y, (1, m))
C = np.full((n, m), c)
M = np.full((n, m), True, dtype=bool)
N = np.zeros((n, m))
for i in range(iterations):
Z[M] = Z[M] * Z[M] + C[M]
M[np.abs(Z) > 2] = False
N[M] = i
# Update the image placeholder by calling the image() function on it.
image.image(1.0 - (N / N.max()), use_column_width=True)
# We clear elements by calling empty on them.
progress_bar.empty()
frame_text.empty()
# Streamlit widgets automatically run the script from top to bottom. Since
# this button is not connected to any other logic, it just causes a plain
# rerun.
st.button("Re-run")

範例三:資料分析

原始程式碼

import streamlit as st
import pandas as pd
import altair as alt
from urllib.error import URLError@st.cache
def get_UN_data():
AWS_BUCKET_URL = "http://streamlit-demo-data.s3-us-west-2.amazonaws.com"
df = pd.read_csv(AWS_BUCKET_URL + "/agri.csv.gz")
return df.set_index("Region")
try:
df = get_UN_data()
countries = st.multiselect(
"Choose countries", list(df.index), ["China", "United States of America"]
)
if not countries:
st.error("Please select at least one country.")
else:
data = df.loc[countries]
data /= 1000000.0
st.write("### Gross Agricultural Production ($B)", data.sort_index())
data = data.T.reset_index()
data = pd.melt(data, id_vars=["index"]).rename(
columns={"index": "year", "value": "Gross Agricultural Product ($B)"}
)
chart = (
alt.Chart(data)
.mark_area(opacity=0.3)
.encode(
x="year:T",
y=alt.Y("Gross Agricultural Product ($B):Q", stack=None),
color="Region:N",
)
)
st.altair_chart(chart, use_container_width=True)
except URLError as e:
st.error(
"""
**This demo requires internet access.**
Connection error: %s
"""
% e.reason
)

範例四:地圖

原始程式碼

import streamlit as st
import pandas as pd
import pydeck as pdk
from urllib.error import URLError@st.cache
def from_data_file(filename):
url = (
"http://raw.githubusercontent.com/streamlit/"
"example-data/master/hello/v1/%s" % filename)
return pd.read_json(url)
try:
ALL_LAYERS = {
"Bike Rentals": pdk.Layer(
"HexagonLayer",
data=from_data_file("bike_rental_stats.json"),
get_position=["lon", "lat"],
radius=200,
elevation_scale=4,
elevation_range=[0, 1000],
extruded=True,
),
"Bart Stop Exits": pdk.Layer(
"ScatterplotLayer",
data=from_data_file("bart_stop_stats.json"),
get_position=["lon", "lat"],
get_color=[200, 30, 0, 160],
get_radius="[exits]",
radius_scale=0.05,
),
"Bart Stop Names": pdk.Layer(
"TextLayer",
data=from_data_file("bart_stop_stats.json"),
get_position=["lon", "lat"],
get_text="name",
get_color=[0, 0, 0, 200],
get_size=15,
get_alignment_baseline="'bottom'",
),
"Outbound Flow": pdk.Layer(
"ArcLayer",
data=from_data_file("bart_path_stats.json"),
get_source_position=["lon", "lat"],
get_target_position=["lon2", "lat2"],
get_source_color=[200, 30, 0, 160],
get_target_color=[200, 30, 0, 160],
auto_highlight=True,
width_scale=0.0001,
get_width="outbound",
width_min_pixels=3,
width_max_pixels=30,
),
}
st.sidebar.markdown('### Map Layers')
selected_layers = [
layer for layer_name, layer in ALL_LAYERS.items()
if st.sidebar.checkbox(layer_name, True)]
if selected_layers:
st.pydeck_chart(pdk.Deck(
map_style="mapbox://styles/mapbox/light-v9",
initial_view_state={"latitude": 37.76,
"longitude": -122.4, "zoom": 11, "pitch": 50},
layers=selected_layers,
))
else:
st.error("Please choose at least one layer above.")
except URLError as e:
st.error("""
**This demo requires internet access.**
Connection error: %s
""" % e.reason)

作者:Yungger 勇哥

若覺得此文真對您有幫助, 點點左上方的拍手圖示, 鼓勵一下。若還想 請喝杯咖啡 鼓勵一下勇哥的繼續創作, 也感謝 😘 😘 !!

Yungger

Maker & Freelancer

--

--

Maker & Freelancer

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store