Dash框架



本章將詳細討論Dash框架。

Dash是一個開源的Python框架,用於構建分析型Web應用程式。它是一個強大的庫,簡化了資料驅動應用程式的開發。它尤其適用於不太熟悉Web開發的Python資料科學家。使用者可以使用Dash在瀏覽器中建立令人驚歎的儀表板。

Dash建立在Plotly.js、React和Flask之上,它將現代UI元素(如下拉選單、滑塊和圖表)直接繫結到您的分析型Python程式碼。

Dash應用程式由一個Flask伺服器組成,該伺服器使用HTTP請求透過JSON資料包與前端React元件通訊。

Dash應用程式完全用Python編寫,因此無需HTML或JavaScript。

Dash安裝

如果您的終端中尚未安裝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_componentsdash_core_components庫構建佈局。Dash為應用程式的所有可視元件提供了Python類。我們還可以使用JavaScript和React.js自定義我們自己的元件。

import dash_core_components as dcc

import dash_html_components as 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應用程式

我們將學習如何使用上述庫在檔案dashApp.py中編寫一個簡單的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(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:32:39] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [12/Aug/2018 09:32:42] "GET /_dash-layout HTTP/1.1" 200 -
127.0.0.1 - - [12/Aug/2018 09:32:42] "GET /_dash-dependencies HTTP/1.1" 200 -
127.0.0.1 - - [12/Aug/2018 09:32:42] "GET /favicon.ico HTTP/1.1" 200 -
127.0.0.1 - - [12/Aug/2018 09:39:52] "GET /favicon.ico HTTP/1.1" 200 -

在您的Web瀏覽器中訪問http://127.0.0.1:8050/。您應該會看到一個如下所示的應用程式。

Hello Dash

在上述程式中,需要注意以下幾點:

  • 應用程式佈局由“元件”(如html.Div和dcc.Graph)組成的樹組成。

  • dash_html_components庫為每個HTML標籤提供了一個元件。html.H1 (children = ‘Hello Dash’)元件在您的應用程式中生成一個<h1> Hello Dash </h1> HTML元素。

  • 並非所有元件都是純HTML。dash_core_components描述了更高級別的元件,這些元件具有互動性,並透過React.js庫使用JavaScript、HTML和CSS生成。

  • 每個元件都完全透過關鍵字屬性來描述。Dash是宣告式的:您主要透過這些屬性來描述您的應用程式。

  • children屬性是特殊的。按照慣例,它始終是第一個屬性,這意味著您可以省略它。

  • 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中的style屬性,您可以只提供一個字典,而在HTML中,它是一個用分號分隔的字串。

  • 樣式字典鍵是駝峰式的,因此text-align更改為textalign

  • Dash中的ClassName類似於HTML class屬性。

  • 第一個引數是HTML標籤的子元素,透過children關鍵字引數指定。

可重用元件

透過用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 Input'),
   dcc.Input(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庫生成更高級別的元件,如控制元件和圖表。

廣告