01.Python Dash网页开发:环境配置和初试

Dash类似R语言中的Shiny包,可以使用纯Python代码而不需要学习HTML、CSS、JavaScript语言就可以快速搭建一个网站,dash-bootstrap-components是Dash的拓展,提供了很多特性。

 

official site

Dash

https://dash.plotly.com/

 

dash-bootstrap-components(dbc)

https://dash-bootstrap-components.opensource.faculty.ai/

 

conda环境配置

我一直使用的是micromamba,因为比conda速度快,语法和conda一样,其中Dash网站所需要的4个包名字是dash开头,其他包是平时数据分析所需要用的;这里并未指定Python版本,自动安装的python是最新版3.10。

 

micromamba create -n dash;micromamba activate dash

micromamba -y install -c anaconda ipywidgets pandas numpy seaborn scikit-learn

micromamba -y install -c conda-forge matplotlib ipykernel dash dash-core-components dash-html-components dash-bootstrap-components

Dash网页APP初试

这里使用的是dbc官网的案例,模仿Shiny包使用KMeans给iris数据集聚类。

 

先不用管代码怎么写的,先跑起来。

 

新进一个文件iris_dash.py把下边代码复制进去。

 

"""

Dash port of Shiny iris k-means example:

 

https://shiny.rstudio.com/gallery/kmeans-example.html

"""

import dash

import dash_bootstrap_components as dbc

import pandas as pd

import plotly.graph_objs as go

from dash import Input, Output, dcc, html

from sklearn import datasets

from sklearn.cluster import KMeans

 

iris_raw = datasets.load_iris()

iris = pd.DataFrame(iris_raw["data"], columns=iris_raw["feature_names"])

 

app = dash.Dash(external_stylesheets=[dbc.themes.BOOTSTRAP])

 

controls = dbc.Card(

    [

        html.Div(

            [

                dbc.Label("X variable"),

                dcc.Dropdown(

                    id="x-variable",

                    options=[

                        {"label": col, "value": col} for col in iris.columns

                    ],

                    value="sepal length (cm)",

                ),

            ]

        ),

        html.Div(

            [

                dbc.Label("Y variable"),

                dcc.Dropdown(

                    id="y-variable",

                    options=[

                        {"label": col, "value": col} for col in iris.columns

                    ],

                    value="sepal width (cm)",

                ),

            ]

        ),

        html.Div(

            [

                dbc.Label("Cluster count"),

                dbc.Input(id="cluster-count", type="number", value=3),

            ]

        ),

    ],

    body=True,

)

 

app.layout = dbc.Container(

    [

        html.H1("Iris k-means clustering"),

        html.Hr(),

        dbc.Row(

            [

                dbc.Col(controls, md=4),

                dbc.Col(dcc.Graph(id="cluster-graph"), md=8),

            ],

            align="center",

        ),

    ],

    fluid=True,

)

 

 

@app.callback(

    Output("cluster-graph", "figure"),

    [

        Input("x-variable", "value"),

        Input("y-variable", "value"),

        Input("cluster-count", "value"),

    ],

)

def make_graph(x, y, n_clusters):

    # minimal input validation, make sure there's at least one cluster

    km = KMeans(n_clusters=max(n_clusters, 1))

    df = iris.loc[:, [x, y]]

    km.fit(df.values)

    df["cluster"] = km.labels_

 

    centers = km.cluster_centers_

 

    data = [

        go.Scatter(

            x=df.loc[df.cluster == c, x],

            y=df.loc[df.cluster == c, y],

            mode="markers",

            marker={"size": 8},

            name="Cluster {}".format(c),

        )

        for c in range(n_clusters)

    ]

 

    data.append(

        go.Scatter(

            x=centers[:, 0],

            y=centers[:, 1],

            mode="markers",

            marker={"color": "#000", "size": 12, "symbol": "diamond"},

            name="Cluster centers",

        )

    )

 

    layout = {"xaxis": {"title": x}, "yaxis": {"title": y}}

 

    return go.Figure(data=data, layout=layout)

 

 

# make sure that x and y values can't be the same variable

def filter_options(v):

    """Disable option v"""

    return [

        {"label": col, "value": col, "disabled": col == v}

        for col in iris.columns

    ]

# functionality is the same for both dropdowns, so we reuse filter_options

app.callback(Output("x-variable", "options"), [Input("y-variable", "value")])(

    filter_options

)

app.callback(Output("y-variable", "options"), [Input("x-variable", "value")])(

    filter_options

)

 

 

if __name__ == "__main__":

    app.run_server(debug=True, port=8888)

 

在terminal中运行

 

micromamba activate dash

python iris_dash.py

打开浏览器http://127.0.0.1:8888/#,一个交互式网页APP就OK了。

 

图片

a9fb7eaa3c3348418316067ccdc1210c.jpg

 

  • 25
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python Dash是一个基于Flask和React.js的开源的Web应用框架,用于创建交互式和数据驱动的仪表盘。它允许使用Python的简洁语法进行开发,并提供了丰富的功能和组件,使得创建仪表盘变得简单而快捷。 Python Dash可以用于各种案例和应用场景。下面是一些常见的Python Dash案例: 1. 数据分析仪表盘:Python Dash可以从各种数据源中提取数据,并通过可视化图表和图形展示数据的分析结果。这可以用于数据分析师、业务分析师和决策者来实时监控和分析关键数据指标。 2. 实时监控仪表盘:Python Dash可以通过与传感器、数据库或其他数据源的连接,实现实时数据的监控和展示。这适用于物联网设备监控、生产线监控、服务器性能监控等应用。 3. 数据可视化应用:Python Dash提供了丰富的数据可视化组件,可以将数据以交互式和动态的方式展示出来。这可以用于创建在线报告、数据洞察、市场趋势等可视化应用。 4. 自定义控件面板:Python Dash可以通过自定义布局和控件来创建定制化的面板和工具。这可以用于创建调试工具、参数配置界面、机器学习模型调优界面等。 总而言之,Python Dash提供了一种简单而强大的方式来创建交互式的Web应用和仪表盘。它可以与其他Python库和工具无缝集成,为开发者提供了广泛的应用场景和定制化功能。无论是数据分析、实时监控还是数据可视化等领域,Python Dash都是一个理想的选择。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值