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

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

作者: 生信探索 | 来源:发表于2024-04-25 05:51 被阅读0次

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了。

图片


相关文章

  • 01.python开发环境配置

    开发环境配置: windows开发环境配置 从Python的官方网站下载32或者64位安装程序安装即可. Mac开...

  • 01.python开发环境配置介绍

    1.python开发环境配置介绍 1、开发环境介绍: 1.1 anaconda: 官网:https://www.a...

  • Dart 基础训练

    环境安装 Dart 环境 开发工具 VS Code + Flutter 插件 + Dash 基础语法 变量 dar...

  • vue3.0 多环境配置

    最常见的多环境配置,就是开发环境配置,和生产环境配置(也就是上线的配置),很多情况下我们开发环境下的域名,和一些配...

  • 关于idea配置struct2+MySQL+tomcat并建立一

    struct2&tomcat的配置 实验课的要求是使用eclipse进行网页的开发,但是各种环境配置巨麻烦,就使用...

  • Nginx https环境配置

    本文主要讲述如何配置本地Nginx开发环境,重点讲述其对https支持的配置。 起源 近期在做网页加载速度优化,准...

  • 全局变量

    可以通过配置全局变量,全局配置请求域名以区分开发环境、测试环境、编译环境等等通过.env配置环境变量区分开发和生产...

  • webpack基础下

    开发环境和生产环境的配置 1、分别创建开发和生产2个配置webpack.xx.js文件,共同的配置部分放公共js,...

  • 使用Java+Tomcat搭建远端服务器

    前言 上一篇介绍了京东云主机的登录和简单的静态网页配置。 这一篇主要讲述服务器开发环境的配置和部署。 首先,实现服...

  • Webpack入门之二:实战配置开发和线上环境

    如何配置开发和线上环境 开发环境配置 安装 webpack-dev-server 在package.json的sc...

网友评论

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

      本文链接:https://www.haomeiwen.com/subject/yhtnxjtx.html