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快速创建仪表盘的详细内容。

大家都在看:

  • 我的微信
  • 这是我的微信扫一扫
  • weinxin
  • 设计福利助手
  • 我的微信公众号扫一扫
  • weinxin

发表评论

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