Python使用Streamlit快速創(chuàng)建儀表盤

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

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

前言

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

pip install streamlit

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

創(chuàng)建儀表盤

首先我們先看看實現(xiàn)后的效果吧!

Python使用Streamlit快速創(chuàng)建儀表盤

Python使用Streamlit快速創(chuàng)建儀表盤

在下面,我們?yōu)槟峁┝藘x表板的代碼。

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() 函數(shù)將頁面布局設(shè)置為 "wide"。

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

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

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

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

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

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

以上就是Python使用Streamlit快速創(chuàng)建儀表盤的詳細內(nèi)容。

歷史上的今天:

推薦應(yīng)用

發(fā)表評論

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