Dash 框架


在本章中,我们将详细讨论 Dash 框架。

Dash 是一个用于构建分析 Web 应用程序的开源 Python 框架。它是一个功能强大的库,可简化数据驱动应用程序的开发。它对不熟悉 Web 开发的 Python 数据科学家特别有用。用户可以使用 dash 在浏览器中创建令人惊叹的仪表板。

Dash 建立在 Plotly.js、React 和 Flask 之上,将下拉、滑块和图形等现代 UI 元素直接与你的分析 Python 代码联系起来。

Dash 应用程序由一个 Flask 服务器组成,该服务器使用 JSON 数据包通过 HTTP 请求与前端 React 组件进行通信。

Dash 应用程序纯粹用 python 编写,因此不需要 HTML 或 JavaScript。

短跑设置


如果你的终端中尚未安装 Dash,请安装下面提到的 Dash 库。由于这些库正在积极开发中,因此请经常安装和升级。还支持 Python 2 和 3。

  • pip install dash==0.23.1 # 核心dash后端
  • pip install dash-renderer==0.13.0 # dash前端
  • pip install dash-html-components==0.11.0 # HTML 组件
  • pip install dash-core-components==0.26.0 # 增压组件
  • pip install plotly==3.1.0 # Plotly 图形库

为了确保一切正常,在这里,我们创建了一个简单的 dashApp.py 文件。

Dash 或应用程序布局


Dash 应用程序由两部分组成。第一部分是应用程序的“布局”,它基本上描述了应用程序的外观。第二部分描述了应用程序的交互性。

核心组件


我们可以用 dash_html_components and the dash_core_components 图书馆。 Dash 为应用程序的所有可视化组件提供了 python 类。我们还可以使用 JavaScript 和 React.js 自定义我们自己的组件。

将 dash_core_components 导入为 dcc

将 dash_html_components 导入为 html

dash_html_components 用于所有 HTML 标签,其中 dash_core_components 用于使用 React.js 构建的交互性。

使用以上两个库,让我们编写如下代码:

app = dash.Dash()
app.layout = html.Div(children=[
    html.H1(children='Hello Dash'),
    html.Div(children='''Dash Framework: A web application framework for Python.''')

等效的 HTML 代码如下所示:

<div>
    <h1> Hello Dash </h1>
    <div> Dash Framework: A web application framework for Python. </div>
</div>

编写简单的 Dash 应用程序


我们将学习如何在文件中使用上述库编写一个简单的Dash 示例 dashApp.py .

# -*- coding: utf-8 -*-
import dash
import dash_core_components as dcc
import dash_html_components as html

app = dash.Dash()
app.layout = html.Div(children=[
    html.H1(children='Hello Dash'),
    html.Div(children='''Dash Framework: A web application framework for Python.'''),
	
    dcc.Graph(
        id='example-graph',
        figure={
            'data': [
                {'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': 'Delhi'},
                {'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name': u'Mumbai'},
            ],
            'layout': {
                'title': 'Dash Data Visualization'
            }
        }
    )
])

if __name__ == '__main__':
    app.run_server(debug=True)

运行 Dash 应用程序


运行 Dash 应用程序时请注意以下几点。

(MyDjangoEnv) C:\Users\rajesh\Desktop\MyDjango\dash>python dashApp1.py

  • 服务 Flask 应用程序“dashApp1”(延迟加载)

  • 环境:生产

    警告:不要在生产环境中使用开发服务器。

    请改用生产 WSGI 服务器。

  • 调试模式:开

  • 用 stat 重启

  • 调试器处于活动状态!

  • 调试器 PIN:130-303-947

  • 继续运行 http://127.0.0.1:8050/ (按 CTRL+C 退出)

127.0.0.1 - - [12/Aug/2018 09服务 Flask 应用程序“dashApp1”(延迟加载)39] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [12/Aug/2018 09服务 Flask 应用程序“dashApp1”(延迟加载)42] "GET /_dash-layout HTTP/1.1" 200 -
127.0.0.1 - - [12/Aug/2018 09服务 Flask 应用程序“dashApp1”(延迟加载)42] "GET /_dash-dependencies HTTP/1.1" 200 -
127.0.0.1 - - [12/Aug/2018 09服务 Flask 应用程序“dashApp1”(延迟加载)42] "GET /favicon.ico HTTP/1.1" 200 -
127.0.0.1 - - [12/Aug/2018 09调试器 PIN:130-303-94752] "GET /favicon.ico HTTP/1.1" 200 -

Visit http:127.0.0.1:8050/ 在你的网络浏览器中。你应该看到一个看起来像这样的应用程序。

Hello Dash

在上述程序中,需要注意的几个要点如下:

  • 应用程序布局由“组件”树组成,例如 html.Div 和 dcc.Graph。

  • dash_html_components 库对每个 HTML 标记都有一个组件。 html.H1 (children = ‘Hello Dash’) 组件在你的应用程序中生成一个

    Hello Dash

    HTML 元素。

  • 并非所有组件都是纯 HTML。 dash_core_components 描述了更高级别的交互式组件,这些组件是通过 React.js 库使用 JavaScript、HTML 和 CSS 生成的。

  • 每个组件都完全通过关键字属性进行描述。 Dash 是声明性的:你将主要通过这些属性来描述你的应用程序。

  • 孩子们的财产很特别。按照惯例,它始终是第一个属性,这意味着你可以省略它。

  • Html.H1 (children='Hello Dash') 与 html.H1 ('Hello Dash') 相同。

  • 应用程序中的字体看起来与此处显示的字体略有不同。此应用程序使用自定义 CSS 样式表来修改元素的默认样式。自定义字体样式是允许的,但截至目前,我们可以添加以下 URL 或你选择的任何 URL:

    app.css.append_css ({“external_url”: https://codepen.io/chriddyp/pen/bwLwgP.css }) 让你的文件获得与这些示例相同的外观。

更多关于 HTML


dash_html_components 库包含每个 HTML 标记的组件类以及所有 HTML 参数的关键字参数。

让我们在之前的应用文本中添加组件的内联样式:

# -*- coding: utf-8 -*-
import dash
import dash_core_components as dcc
import dash_html_components as html

app = dash.Dash()
colors = {
    'background': '#87D653',
    'text': '#ff0033'
}

app.layout = html.Div(style={'backgroundColor': colors['background']}, children=[
    html.H1(
        children='Hello Dash',
        style={
            'textAlign': 'center',
            'color': colors['text']
        }
    ),
	
    html.Div(children='Dash: A web application framework for Python.', style={
        'textAlign': 'center',
        'color': colors['text']
    }),
	
    dcc.Graph(
        id='example-graph-2',

        figure={
            'data': [
                {'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': 'Delhi'},
                {'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name': u'Mumbai'},
            ],
            'layout': {
                'plot_bgcolor': colors['background'],
                'paper_bgcolor': colors['background'],
                'font': {
                    'color': colors['text']
                }
            }
        }
    )
])

if __name__ == '__main__':
    app.run_server(debug=True)

在上面的示例中,我们使用 style 属性修改了 html.Div 和 html.H1 组件的内联样式。

Style Property

在 Dash 应用程序中呈现如下:

Data Application

dash_html_components 和 HTML 属性之间有几个关键区别:

  • 对于 Dash 中的样式属性,你可以只提供一个字典,而在 HTML 中,它是分号分隔的字符串。

  • 样式字典键是 骆驼装 ,所以 text-align 更改为 文本对齐 .

  • Dash 中的 ClassName 类似于 HTML 的类属性。

  • 第一个参数是通过 children 关键字参数指定的 HTML 标记的子代。

可重用组件


通过用 Python 编写我们的标记,我们可以创建复杂的可重用组件,如表格,而无需切换上下文或语言:

下面是一个从 pandas 数据帧生成“表格”的快速示例。

import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd

df = pd.read_csv(
    'https:// gist.githubusercontent.com/chriddyp/'
    'c78bf172206ce24f77d6363a2d754b59/raw/'
    'c353e8ef842413cae56ae3920b8fd78468aa4cb2/'
    'usa-agricultural-exports-2011.csv')
	
def generate_table(dataframe, max_rows=10):
    return html.Table(
        # Header
        [html.Tr([html.Th(col) for col in dataframe.columns])] +
        # Body
        [html.Tr([
            html.Td(dataframe.iloc[i][col]) for col in dataframe.columns
        ]) for i in range(min(len(dataframe), max_rows))]
    )
	
app = dash.Dash()
app.layout = html.Div(children=[
    html.H4(children='US Agriculture Exports (2011)'),
    generate_table(df)
])

if __name__ == '__main__':
    app.run_server(debug=True)

我们的输出会是这样的:

Reusable Components

更多关于可视化


dash_core_components 库包含一个名为 Graph .

Graph 使用开源 plotly.js JavaScript 图形库呈现交互式数据可视化。 Plotly.js 支持大约 35 种图表类型,并以矢量质量 SVG 和高性能 WebGL 呈现图表。

下面是一个从 Pandas 数据框创建散点图的示例:

import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import plotly.graph_objs as go

app = dash.Dash()

df = pd.read_csv(
    'https:// gist.githubusercontent.com/chriddyp/' +
    '5d1ea79569ed194d432e56108a04d188/raw/' +
    'a9f9e8076b837d541398e999dcbac2b2826a81f8/'+
    'gdp-life-exp-2007.csv')
	
app.layout = html.Div([
    dcc.Graph(
        id='life-exp-vs-gdp',
        figure={
            'data': [
                go.Scatter(
                    x=df[df['continent'] == i]['gdp per capita'],
                    y=df[df['continent'] == i]['life expectancy'],
                    text=df[df['continent'] == i]['country'],
                    mode='markers',
                    opacity=0.7,
                    marker={
                        'size': 15,
                        'line': {'width': 0.5, 'color': 'white'}
                    },
                    name=i
                ) for i in df.continent.unique()
            ],
            'layout': go.Layout(
                xaxis={'type': 'log', 'title': 'GDP Per Capita'},
                yaxis={'title': 'Life Expectancy'},
                margin={'l': 40, 'b': 40, 't': 10, 'r': 10},
                legend={'x': 0, 'y': 1},
                hovermode='closest'
            )
        }
    )
])

if __name__ == '__main__':
    app.run_server()

上述代码的输出如下:

Visualization

这些图表是交互式的和响应式的。你可以将鼠标悬停在点上以查看其值,单击图例项以切换轨迹,单击并拖动以缩放,按住 shift 并单击并拖动以平移。

Markdown


虽然 dash 通过 dash_html_components 库公开了 HTML 风格,但用 HTML 编写副本可能很乏味。要编写文本块,你可以使用 dash_core_components 库中的 Markdown 组件。

核心组件


dash_core_components 包括一组更高级别的组件,如下拉列表、图表、markdown、块等等。

与所有其他 Dash 组件一样,它们完全以声明方式描述。每个可配置的选项都可用作组件的关键字参数。

下面是示例,使用了一些可用的组件:

# -*- coding: utf-8 -*-
import dash
import dash_core_components as dcc
import dash_html_components as html

app = dash.Dash()

app.layout = html.Div([
    html.Label('Dropdown'),
    dcc.Dropdown(
        options=[
            {'label': 'New York City', 'value': 'NYC'},
            {'label': u'Montréal', 'value': 'MTL'},
            {'label': 'San Francisco', 'value': 'SF'}
        ],
        value='MTL'
    ),
	
    html.Label('Multi-Select Dropdown'),
    dcc.Dropdown(
        options=[
            {'label': 'New York City', 'value': 'NYC'},
            {'label': u'Montréal', 'value': 'MTL'},
            {'label': 'San Francisco', 'value': 'SF'}
        ],
        value=['MTL', 'SF'],
        multi=True
    ),
	
    html.Label('Radio Items'),
    dcc.RadioItems(
        options=[
            {'label': 'New York City', 'value': 'NYC'},
            {'label': u'Montréal', 'value': 'MTL'},
            {'label': 'San Francisco', 'value': 'SF'}
        ],
        value='MTL'
    ),
	
    html.Label('Checkboxes'),
    dcc.Checklist(
        options=[
            {'label': 'New York City', 'value': 'NYC'},
            {'label': u'Montréal', 'value': 'MTL'},
            {'label': 'San Francisco', 'value': 'SF'}
        ],
        values=['MTL', 'SF']
    ),

    html.Label('Text 输入'),
    dcc.输入(value='MTL', type='text'),
	
    html.Label('Slider'),
    dcc.Slider(
        min=0,
        max=9,
        marks={i: 'Label {}'.format(i) if i == 1 else str(i) for i in range(1, 6)},
        value=5,
    ),
], style={'columnCount': 2})

if __name__ == '__main__':
    app.run_server(debug=True)

上述程序的输出如下:

Core Components

呼叫帮助


Dash 组件是声明性的。这些组件的每个可配置方面都在安装期间设置为关键字参数。你可以在任何组件的 python 控制台中调用帮助,以了解有关组件及其可用参数的更多信息。其中一些如下:

>>> help(dcc.Dropdown)
Help on class Dropdown in module builtins:
class Dropdown(dash.development.base_component.Component)
| A Dropdown component.
| Dropdown is an interactive dropdown element for selecting one or more

| items.
| The values and labels of the dropdown items are specified in the `options`
| property and the selected item(s) are specified with the `value` property.
|
| Use a dropdown when you have many options (more than 5) or when you are
| constrained for space. Otherwise, you can use RadioItems or a Checklist,
| which have the benefit of showing the users all of the items at once.
|
| Keyword arguments:
| - id (string; optional)
| - options (list; optional): An array of options
| - value (string | list; optional): The value of the input. If `multi` is false (the default)
-- More --

总而言之,Dash 应用程序的布局描述了应用程序的外观。布局是组件的层次结构树。 dash_html_components 库为所有 HTML 标记和关键字参数提供类,并描述 HTML 属性,如 style、className 和 id。 dash_core_components 库生成更高级别的组件,如控件和图形。