【呆鳥譯Py】Dash用戶指南01-02_安裝與應(yīng)用布局

封面

【呆鳥譯Py】Python交互式數(shù)據(jù)分析報(bào)告框架~Dash介紹
【呆鳥譯Py】Dash用戶指南01-02_安裝與應(yīng)用布局
【呆鳥譯Py】Dash用戶指南03_交互性簡介
【呆鳥譯Py】Dash用戶指南04_交互式數(shù)據(jù)圖
【呆鳥譯Py】Dash用戶指南05_使用State進(jìn)行回調(diào)

1. 安裝

Dash需要安裝以下幾個(gè)庫才能正常使用,這些庫仍在不斷更新,請(qǐng)注意及時(shí)升級(jí)。

Dash支持Python2與Python3。

pip install dash==0.25.0  # Dash核心后端
pip install dash-renderer==0.13.2  # Dash前端
pip install dash-html-components==0.11.0  # HTML組件
pip install dash-core-components==0.27.1  # Dash核心組件
pip install plotly --upgrade  # Plotly圖形庫

譯注:通過以下鏈接查看Dash及其支持庫的最新版本。

2. Dash應(yīng)用布局

本教程通過6個(gè)例子介紹如何創(chuàng)建Dash應(yīng)用。

使用Dash生成HTML

Dash應(yīng)用由兩部分組成,第一部分是應(yīng)用的布局layout,描述應(yīng)用的設(shè)計(jì)樣式。第二部分描述應(yīng)用的交互性。

Dash為每個(gè)可視化組件都提供了Python類,Plotly提供的dash_core_componentsdash_html_components組件庫包含了一系列Dash組件,如果這些還不夠,可以使用JavaScript 和React.js創(chuàng)建更多組件。
首先,新建 app.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='你好,Dash'),

    html.Div(children='''
        Dash: Python網(wǎng)絡(luò)應(yīng)用框架'''),

    dcc.Graph(
        id='example-graph',
        figure={
            'data': [
                {'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': '北京'},
                {'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name': '天津'},
            ],
            'layout': {
                'title': 'Dash數(shù)據(jù)可視化'
            }
        }
    )
])

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

運(yùn)行以下語句:

$ python app.py
...Running on http://127.0.0.1:8050/ (Press CTRL+C to quit)

在瀏覽器中訪問 http://127.0.0.1:8050/ ,就可看到下圖所示內(nèi)容。

001

注意:

  1. layouthtml.Divdcc.Graph這樣的組件樹組成。
  2. dash_html_components 庫為每個(gè)HTML標(biāo)簽都提供了對(duì)應(yīng)的組件。html.H1(children='你好,Dash') 組件可以生成<h1>你好,Dash</h1>這樣的HTML語句。
  3. 并非所有組件都使用純HTML語言。dash_core_components 這種交互式高階組件庫,就是由JavaScript、HTML和CSS編寫,并由React.js庫生成的。
  4. Dash是聲明式的,可以用關(guān)鍵字的屬性描述組件。即,Dash主要通過屬性描述應(yīng)用。
  5. children特性[1]有些特殊。一般來說,它是第一個(gè)屬性[2],可以省略:html.H1(children = '你好, Dash')html.H1('你好,Dash')的效果一樣。此特性支持字符串、數(shù)字、單個(gè)組件或組件列表。
  6. 你的應(yīng)用字體看上去可能與本教程顯示的不一樣,這是因?yàn)楸窘坛痰膽?yīng)用使用了自定義CSS樣式,修改了默認(rèn)元素的格式。要了解更多內(nèi)容,可以查閱CSS教程。如果需要,可以添加app.css.append_css({"external_url": "https://codepen.io/chriddyp/pen/bWLwgP.css"})至本文件,就能呈現(xiàn)出與本例相同的效果。

關(guān)于HTML更多的內(nèi)容

dash_html_components 庫除了為HTML參數(shù)提供了關(guān)鍵字外,還為每個(gè)HTML標(biāo)簽提供了組件類。

在Dash應(yīng)用中,可以使用以下代碼通過組件的行內(nèi)樣式修改自定義文本。

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

app = dash.Dash()

colors = {
    'background': '#111111',
    'text': '#7FDBFF'
}

app.layout = html.Div(style={'backgroundColor': colors['background']},
                      children=[
    html.H1(
        children='你好,Dash',
        style={
            'textAlign': 'center',
            'color': colors['text']
        }
    ),
    html.Div(children='Dash:Python網(wǎng)絡(luò)應(yīng)用框架', 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':'北京'},
                {'x': [1, 2, 3], 'y':[2, 4, 5], 'type':'bar', 'name':'天津'},
            ],
            'layout':{
                'plot_bgcolor': colors['background'],
                'paper_bgcolor': colors['background'],
                'font':{
                    'color': colors['text']
                }
            }
        }

    )

])

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

本例中,用style特性修改html.Divhtml.H1組件的行內(nèi)樣式。

Dash應(yīng)用把html.H1('你好,Dash', style={'textAlign': 'center', 'color': '#7FDFF'}) 渲染為 <h1 style="text-align: center; color: #7FDFF">你好,Dash</h1>。

dash_html_components與HTML屬性有以下幾點(diǎn)顯著區(qū)別:

  1. HTML的style特性是用分號(hào)分割的字符串,Dash用的是字典;
  2. Dash的style字典關(guān)鍵字是駝峰式,相對(duì)于HTML的text-align,Dash是textAlign;
  3. HTML的class屬性在Dash中是className;
  4. HTML標(biāo)簽的子項(xiàng)(即children)是通過children關(guān)鍵字指定的。一般來說,作為第一個(gè)參數(shù),可以省略。

除此之外,其他所有HTML屬性與標(biāo)簽在Python中都有效。

可復(fù)用組件

在Python中寫入標(biāo)記符號(hào)(Markup),即可創(chuàng)建表格等可復(fù)用組件,無需切換環(huán)境或語言。

下面是用Pandas DataFrame生成表格的例子。

# -*- coding: utf-8 -*-
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_talbe(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.css.append_css(
    {"external_url": "https://codepen.io/chriddyp/pen/bWLwgP.css"})

app.layout = html.Div(children=[
    html.H4(children='2011年美國農(nóng)業(yè)出口數(shù)據(jù)表'),
    generate_talbe(df)
])
if __name__ == '__main__':
    app.run_server(debug=True)
003

可視化示例

下面的例子用Pandas DataFrame創(chuàng)建散點(diǎn)圖。

# -*- coding: utf-8 -*-
import dash
import pandas as pd
import plotly.graph_objs as go
import dash_core_components as dcc
import dash_html_components as html

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'},
                yaxis={'title': '平均壽命'},
                margin={'l': 40, 'b': 40, 't': 10, 'r': 10},
                legend={'x': 0, 'y': 1},
                hovermode='closest'
            )
        }
    )
])

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

這些圖支持交互響應(yīng)。鼠標(biāo)懸浮在點(diǎn)上可查看數(shù)據(jù)的值,點(diǎn)擊圖例可切換展示的內(nèi)容,點(diǎn)擊拖拽可縮放圖形,按下Shift鍵,再點(diǎn)擊拖拽可挪動(dòng)圖形內(nèi)容。

Dash與Markdown

通過dash_html_components庫可以顯示HTML的內(nèi)容,但是,直接寫HTML語句非??菰铩H缧枰獙懭氪罅康母袷交谋?,可使用dash_core_components庫中Markdown組件。

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

app = dash.Dash()

Markdown_text = '''
#### 標(biāo)題
# 1級(jí)標(biāo)題 \#
## 2級(jí)標(biāo)題 \##

#### 分割線
***

### 粗體斜體
*斜體*,文字兩邊各寫一個(gè)\*星號(hào)

**粗體**,文字兩邊各寫兩個(gè)\*星號(hào)

1. [有提示的鏈接](http://url.com/ "有提示的鏈接")
2. [沒有提示的鏈接](http://url.com/)

#### 表格 不支持
姓名|語文|數(shù)學(xué)|總成績
---|:---|:---:|---:
張三|100|90|190

#### 引用文字
使用\>是一級(jí)引用,使用兩個(gè)>,即>>,是引用里面的引用
>引用文字
>>引用里面的引用
'''

app.css.append_css(
    {"external_url": "https://codepen.io/chriddyp/pen/bWLwgP.css"})

app.layout = html.Div([
    dcc.Markdown(children=Markdown_text)
])

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

Dash支持Markdown,使用CommonMark作為Markdown規(guī)范。如果不了解Markdown,請(qǐng)查閱 60秒Markdown教程,或本文譯者編寫的5分鐘玩轉(zhuǎn)Markdown。

譯注:經(jīng)測試,不支持表格、[TOC]生成目錄、代碼塊等

核心組件

dash_core_components庫包含了一組高階組件,包括下拉菜單、圖形、Markdown等等。

和其它Dash組件一樣,這些組件都是聲明式的,組件的關(guān)鍵字參數(shù)也一樣,每個(gè)選項(xiàng)都可以進(jìn)行配置。

本教程將逐一介紹這些組件,在Dash核心組件示例庫中也可以查看這些組件。

下面是一些常用的組件:

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

app = dash.Dash()

app.css.append_css(
    {"external_url": "https://codepen.io/chriddyp/pen/bWLwgP.css"})

app.layout = html.Div([
    html.Label('下拉菜單'),
    dcc.Dropdown(
        options=[
            {'label': '北京', 'value': '北京'},
            {'label': '天津', 'value': '天津'},
            {'label': '上海', 'value': '上海'}
        ],
        value='北京'
    ),

    html.Label('多選下拉菜單'),
    dcc.Dropdown(
        options=[
            {'label': '北京', 'value': '紐約'},
            {'label': '天津', 'value': '天津'},
            {'label': '上海', 'value': '上海'}
        ],
        value=['天津', '上海'],
        multi=True
    ),

    html.Label('單選鈕'),
    dcc.RadioItems(
        options=[
            {'label': '北京', 'value': '紐約'},
            {'label': '天津', 'value': '天津'},
            {'label': '上海', 'value': '上海'}
        ],
        value='天津'
    ),

    html.Label('多選框'),
    dcc.Checklist(
        options=[
            {'label': '北京', 'value': '紐約'},
            {'label': '天津', 'value': '天津'},
            {'label': '上海', 'value': '上海'}
        ],
        values=['天津', '上海']
    ),

    html.Label('文本輸入'),
    dcc.Input(value='天津', type='text'),

    html.Label('滑動(dòng)條'),
    dcc.Slider(
        min=0,
        max=9,
        marks={i: '標(biāo)簽 {}'.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)
006

調(diào)用幫助help

Dash組件是聲明式的:在實(shí)例化關(guān)鍵字參數(shù)時(shí),可設(shè)置可配置項(xiàng)。可在Python控制臺(tái)中調(diào)用幫助help ,查看組件及其參數(shù)的詳細(xì)說明。

>>> help(dcc.Dropdown)
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)
|  - className (string; optional)
|  - disabled (boolean; optional): If true, the option is disabled
|  - multi (boolean; optional): If true, the user can select multiple values
|  - options (list; optional)
|  - placeholder (string; optional): The grey, default text shown when no option is selected
|  - value (string | list; optional): The value of the input. If `multi` is false (the default)
|  then value is just a string that corresponds to the values
|  provided in the `options` property. If `multi` is true, then
|  multiple values can be selected at once, and `value` is an
|  array of items with values corresponding to those in the
|  `options` prop.```

總結(jié)

layout用于描述Dash應(yīng)用的形態(tài),是結(jié)構(gòu)化的樹狀組件。dash_html_components 庫為HTML標(biāo)簽和關(guān)鍵字參數(shù)提供了類,用于描述style 、classNameid 等HTML屬性 。dash_core_componets庫生成控件和圖形等高級(jí)組件。

詳情可查閱:

下一節(jié),介紹如何實(shí)現(xiàn)Dash應(yīng)用交互。

【呆鳥譯Py】Python交互式數(shù)據(jù)分析報(bào)告框架~Dash介紹
【呆鳥譯Py】Dash用戶指南01-02_安裝與應(yīng)用布局
【呆鳥譯Py】Dash用戶指南03_交互性簡介
【呆鳥譯Py】Dash用戶指南04_交互式數(shù)據(jù)圖
【呆鳥譯Py】Dash用戶指南05_使用State進(jìn)行回調(diào)


  1. 此處英文為Property,譯為特性,下同。 ?

  2. 此處英文為Attribute,譯為屬性,下同。 ?

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容