如何使用Streamlit快速创建仪表盘?

上文有快速带大家了解streamlit,因为工作需要,这两天尝试构建了仪表盘,也就是咱们常说的Dashboard,本篇文章将教你如何使用 Streamlit 快速创建一个简单的仪表盘。

前言

Streamlit 可以帮助你轻松创建自定义的数据可视化、互动图表和表格,还能让你通过网络浏览器与他人共享你的作品。它提供了一种简单直观的方法来构建你的网络应用,无需使用 HTML、CSS 或 JavaScript。 在正式开始之前,请确保你已经正确安装了streamlit。

shell 复制代码
pip install streamlit  

在接下来的示例中,我们将创建一个仅包含2个图表和一些用于更改这些图表的小部件的简单仪表板。我认为通过下面的例子非常适合初次接触Streamlit并且希望使用它创建仪表板的人。

创建仪表盘

首先我们先看看实现后的效果吧!

在下面,我们为您提供了仪表板的代码。

python 复制代码
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 参数确保图表填充其各自列中的可用空间。

相关推荐
Ivanqhz8 分钟前
wb 自动化搬运矩阵: 一条定型 “芯片选型偏好” 的话术?!
人工智能·python·机器学习
小白的高手之路9 分钟前
【LeetCode 热题 100】240. 搜索二维矩阵 II|矩阵、二分查找、Z 字形查找(Python)
python·算法·leetcode·矩阵·力扣
geovindu13 分钟前
python:DBSCAN
开发语言·后端·python·算法
斯内普吖17 分钟前
(开源)智慧物业管理系统实战指南 基于 Python + Django + uni-app + Vue + MySQL
vue.js·python·django·uni-app·开源
Ponp_7 小时前
用 StyleGAN2 做图像数据扩充实战
python·深度学习·生成对抗网络
Eyfcom9 小时前
〖物流数据安全 02〗差分隐私与同态加密的工程边界:跨境物流快递系统该为隐私付出多少计算代价?
算法·机器学习·同态加密·跨境物流快递系统·物流数据安全
富贵儿99811 小时前
NL2SQL 实践手记 08:SQL 没报错,答案为什么不对——从失败复盘到 Workflow 修复
数据库·python·sql·ai·自然语言处理·langchain
小虎AI生活11 小时前
实测 Pavo:自动档优先调用免费 Agnes 模型,短剧视频低成本跑通了
aigc·ai编程