Python使用Streamlit快速創建儀表盤

  • A+
所屬分類:百科知識

上文有快速帶大家了解streamlit,因為工作需要,這兩天嘗試構建了儀表盤,也就是咱們常說的Dashboard,本篇文章將教你如何使用 Streamlit 快速創建一個簡單的儀表盤。

前言

Streamlit 可以幫助你輕松創建自定義的數據可視化、互動圖表和表格,還能讓你通過網絡瀏覽器與他人共享你的作品。它提供了一種簡單直觀的方法來構建你的網絡應用,無需使用 HTML、CSS 或 JavaScript。 在正式開始之前,請確保你已經正確安裝了streamlit。

pip install streamlit

在接下來的示例中,我們將創建一個僅包含2個圖表和一些用于更改這些圖表的小部件的簡單儀表板。我認為通過下面的例子非常適合初次接觸Streamlit并且希望使用它創建儀表板的人。

創建儀表盤

首先我們先看看實現后的效果吧!

Python使用Streamlit快速創建儀表盤

Python使用Streamlit快速創建儀表盤

在下面,我們為您提供了儀表板的代碼。

import streamlit as st  
import pandas as pd  
import pandas_bokeh  
from sklearn.datasets import load_wine  
st.set_page_config(layout="wide") ## Set layout wide to cover whole page.  
## Load Data  
@st.cache_data  
def load_data():  
wine = load_wine()  
wine_df = pd.DataFrame(wine.data, columns=wine.feature_names)  
wine_df["WineType"] = [wine.target_names[t] for t in wine.target]  
return wine_df  
wine_df = load_data()  
ingredients = wine_df.drop(columns=["WineType"]).columns  
avg_wine_df = wine_df.groupby("WineType").mean().reset_index()  
## Title  
st.title("Wine Dataset :green[Analysis] :tea: :coffee: :chart: :bar_chart:")  
st.markdown(  
"Wine Analysis dashboard let us explore relationship between various **ingredients** used in creation of 3 different types of wine (*Class_0, Class_1, & Class_2*)")  
## Add Widgets  
st.sidebar.markdown("### Scatter Chart: Explore Relationship Between Ingredients :")  
x_axis = st.sidebar.selectbox("X-Axis", ingredients, )  
y_axis = st.sidebar.selectbox("Y-Axis", ingredients, index=1)  
color_encode = st.sidebar.checkbox(label="Color-Encode by WineType")  
st.sidebar.markdown("### Bar Chart: Average Ingredients Per Wine Type : ")  
bar_multiselect = st.sidebar.multiselect(label="Bar Chart Ingredients", options=ingredients,  
default=["alcohol", "malic_acid", "ash"])  
## Widgets State Change Actions & Layout Adjustments.  
container = st.container()  
chart1, chart2 = container.columns(2)  
with chart1:  
if x_axis and y_axis:  
scatter_fig = wine_df.plot_bokeh.scatter(x=x_axis, y=y_axis, category="WineType" if color_encode else None,  
xlabel=x_axis.capitalize(), ylabel=y_axis.capitalize(),  
title="{} vs {}".format(x_axis.capitalize(), y_axis.capitalize()),  
figsize=(650, 500),  
fontsize_title=25, fontsize_label=12, show_figure=False)  
st.bokeh_chart(scatter_fig, use_container_width=True)  
with chart2:  
if bar_multiselect:  
st.header("Avg Ingredients")  
st.bar_chart(avg_wine_df, x="WineType", y=bar_multiselect, height=500, use_container_width=True)

代碼首先使用 set_page_config() 函數將頁面布局設置為 "wide"。

接著,它使用 'sklearn.datasets' 模塊中的 load_wine() 函數加載葡萄酒數據集,并將其轉換為 Pandas DataFrame。然后,使用 "@st.cache_data" 裝飾器緩存數據,這樣可以在應用程序的后續運行中更快地加載數據。

接下來,代碼創建了一個帶有小部件的側邊欄,用戶可以通過這些小部件選擇散點圖的 x 和 y 軸,以及是否通過葡萄酒類型對點進行顏色編碼。它還包括一個多選小部件,用于選擇在每種葡萄酒類型的平均成分值的柱狀圖中包含哪些成分。

儀表板的主體部分使用 streamlit.container 模塊中的 columns() 函數分為兩列。

在左列中,使用 pandas_bokeh 模塊中的 plot_bokeh.scatter() 函數顯示散點圖,該函數生成一個交互式散點圖。圖表基于用戶選擇的 x 和 y 軸,如果選擇了顏色編碼,可以通過葡萄酒類型對點進行顏色編碼。

右列顯示了每種葡萄酒類型的平均成分值的柱狀圖,這是根據用戶選擇要包含哪些成分而生成的。

最后,代碼使用 Streamlit 庫中的 st.bokeh_chart() 和 st.bar_chart() 函數分別在左列和右列中顯示圖表。streamlit 方法 st.bar_chart() 使用數據可視化庫 Altair 創建圖表。use_container_width=True 參數確保圖表填充其各自列中的可用空間。

以上就是Python使用Streamlit快速創建儀表盤的詳細內容。

歷史上的今天:

推薦應用

發表評論

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: