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

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

前言

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

shell pip install streamlit

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

创建仪表盘

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

image.png

simple<em>dashboard</em>streamlit.jpg

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

```python import streamlit as st
import pandas as pd
import pandasbokeh
from sklearn.datasets import load
wine

st.setpageconfig(layout="wide") ## Set layout wide to cover whole page.

Load Data

@st.cachedata
def load
data():
wine = loadwine()
wine
df = pd.DataFrame(wine.data, columns=wine.featurenames)
wine
df["WineType"] = [wine.targetnames[t] for t in wine.target]
return wine
df

winedf = loaddata()
ingredients = wine_df.drop(columns=["WineType"]).columns

avgwinedf = winedf.groupby("WineType").mean().resetindex()

Title

st.title("Wine Dataset :green[Analysis] :tea: :coffee: :chart: :barchart:")
st.markdown(
"Wine Analysis dashboard let us explore relationship between various ingredients used in creation of 3 different types of wine (*Class
0, Class1, & Class2*)")

Add Widgets

st.sidebar.markdown("### Scatter Chart: Explore Relationship Between Ingredients :")

xaxis = 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 : ")

barmultiselect = 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 xaxis and yaxis:
scatterfig = winedf.plotbokeh.scatter(x=xaxis, y=yaxis, category="WineType" if colorencode else None,
xlabel=xaxis.capitalize(), ylabel=yaxis.capitalize(),
title="{} vs {}".format(xaxis.capitalize(), yaxis.capitalize()),
figsize=(650, 500),
fontsizetitle=25, fontsizelabel=12, showfigure=False)
st.bokeh
chart(scatterfig, usecontainer_width=True)

with chart2:
if barmultiselect:
st.header("Avg Ingredients")
st.bar
chart(avgwinedf, x="WineType", y=barmultiselect, height=500, usecontainer_width=True)

```

代码首先使用 setpageconfig() 函数将页面布局设置为 "wide"。

接着,它使用 'sklearn.datasets' 模块中的 loadwine() 函数加载葡萄酒数据集,并将其转换为 Pandas DataFrame。然后,使用 "@st.cachedata" 装饰器缓存数据,这样可以在应用程序的后续运行中更快地加载数据。

接下来,代码创建了一个带有小部件的侧边栏,用户可以通过这些小部件选择散点图的 x 和 y 轴,以及是否通过葡萄酒类型对点进行颜色编码。它还包括一个多选小部件,用于选择在每种葡萄酒类型的平均成分值的柱状图中包含哪些成分。

仪表板的主体部分使用 streamlit.container 模块中的 columns() 函数分为两列。

在左列中,使用 pandasbokeh 模块中的 plotbokeh.scatter() 函数显示散点图,该函数生成一个交互式散点图。图表基于用户选择的 x 和 y 轴,如果选择了颜色编码,可以通过葡萄酒类型对点进行颜色编码。

右列显示了每种葡萄酒类型的平均成分值的柱状图,这是根据用户选择要包含哪些成分而生成的。

最后,代码使用 Streamlit 库中的 st.bokehchart() 和 st.barchart() 函数分别在左列和右列中显示图表。streamlit 方法 st.barchart() 使用数据可视化库 Altair 创建图表。usecontainer_width=True 参数确保图表填充其各自列中的可用空间。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

facing-screen

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值