
作者 | AlperAydın
來源 | Medium
編輯 | 代碼醫生團隊
原文鏈接:https://cloud.tencent.com/developer/article/1449666
Dash與plotly
交互式數據可視化對探索性數據分析具有重要影響。在將任何描述性或預測性算法應用於數據集之前,必須首先了解這些特征如何相互關聯以及它們如何在內部分布。許多可視化庫提供了滿足此要求的多種類型的圖表。但另一個顯而易見的事情是,為每個功能執行相同的繪圖工作並滾動每個圖表以比較每個功能的結果是一項艱巨的任務。
Plotly是一家數據分析和可視化公司。在這篇文章中,對這家公司的兩個python庫感興趣; plotly.py和dash。Plotly.py庫為python應用程序提供交互式可視化。如網站所示,可以“在Python中創建交互式,D3和WebGL圖表。matplotlib的所有圖表類型等等。
dash與plotly開發文檔:
https://plot.ly/python/
https://dash.plotly.com/
Dash也是同一家公司的另一個產品,為Python構建基於Web的應用程序提供了框架。如果正在與團隊合作或只是想與他人分享工作,那么Web應用程序是最簡單的方法,可以消除庫版本或界面問題。
在這篇文章中,將了解這兩個庫如何成為探索性數據分析的良好解決方案。
一個簡單的短跑應用程序
下面是一個簡單的dash Web應用程序,由六行代碼組成。只需將其寫入.py文件並調用該文件,應用程序即可運行。
#this is the dash_test.py file import dash import dash_html_components as html app = dash.Dash(__name__) app.layout = html.H1('hello dash') if __name__ == '__main__': app.run_server(debug=True, port=8080)
使用文件的確切路徑從命令提示符調用文件如下所示。將看到一個控制台窗口告訴服務器正在運行。
python "c:\users\alper\documents\dash_test.py"

現在可以打開Web瀏覽器並導航到具有給定端口號的localhost URL:127.0.0.1:8080。
在代碼的前兩行中,只需導入所需的dash庫。第三行初始化dash應用程序,第四行使用將在頁面上顯示的標題標記准備頁面布局,最后兩行使用調試和端口選項運行服務器。
首先放置所需的元素。為此將修改app.layout並將一個按鈕和一個標簽元素插入到div中。請注意,這兩個元素作為div元素的子元素放在列表中。Dash在dash_html_components庫中存儲html元素,可以在網站和github repo上找到整個列表。
https://dash.plot.ly/dash-core-components
https://github.com/plotly/dash-html-components/tree/master/src/components
app.layout = html.Div( [ html.Button('create random number', id='button1'), html.Label('...', id='label1') ] )
保存文件時,將在控制台窗口中看到一個帶有新調試器引腳的新行。如果代碼中存在問題,將看到錯誤消息。在這種情況下,需要再次調用該文件並刷新瀏覽器。

現在為插入的元素添加一些樣式。可以使用樣式屬性接受css標記字典的元素添加樣式。
html.Button('create random number', id='button1', style={'display':'block', 'background-color':'#aabbcc'} ), html.Label('...', id='label1', style={'display':'inline-block', 'margin':'10'} )
現在是時候更進一步,增加一些響應能力。首先導入所需的庫
from dash.dependencies import Input, Output import random
然后添加callback decorator和功能,想在回調執行。
@app.callback( Output(component_id=’label1', component_property=’children’), [Input(component_id=’button1', component_property=’n_clicks’)] ) def update_output(input_value): return random.random()
update_output函數只生成一個隨機數並將其作為結果返回。
@ app.callback decorator將按鈕單擊事件綁定到update_output函數,並將函數的結果綁定到label1元素。這是響應能力的核心部分。
添加簡單圖表
由於已經足夠介紹了交互性,現在是時候添加一些圖表了。首先將保持簡單,並在每個按鈕點擊上放置一個帶有隨機值的條形圖。因此需要在布局中添加圖形對象:
app.layout = html.Div( [ html.Button(‘create random number’, id=’button1', style={‘display’:’block’, ‘padding’:’5', ‘background-color’:’#aabbcc’}), html.Label(‘…’, id=’label1', style={‘display’:’inline-block’, ‘margin’:’10'} ), dcc.Graph(id=’graph1') # this is the graph we add ] )
需要修改回調函數來生成圖表:
@app.callback( Output(component_id='graph1', component_property='figure'), [Input(component_id='button1', component_property='n_clicks')] ) def update_output(input_value): random_x = [i for i in range(5)] random_y = [random.random() for _ in range(5)] figure = { 'data': [ {'x':random_x, 'y':random_y, 'type':'bar', 'name': 'Series1'} ], 'layout': { 'title': 'Dash Data Visualization' } } return figure
在callback decorator中,首先用最近添加到布局中的圖形對象替換Output語句中的標簽。然后在函數內部為圖表和圖形對象創建x和y值。結果是瀏覽器中的交互式條形圖。

更復雜一些
如果上面的圖表對你來說不夠用,請不要擔心,這是另一個例子,深入一些。

它太快了嗎?好吧看看代碼。
import random import pandas as pd import dash from dash.dependencies import Input, Output import dash_html_components as html import dash_core_components as dcc import plotly.graph_objs as go app = dash.Dash(__name__) names = [‘sepal-length’, ‘sepal-width’, ‘petal-length’, ‘petal-width’, ‘class’] data = pd.read_csv(‘https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data', names=names) app.layout = html.Div( [ html.Div([ dcc.Dropdown( id=’ddl_x’, options=[{‘label’: i, ‘value’: i} for i in names], value=’sepal-width’, style={‘width’:’50%’} ), dcc.Dropdown( id=’ddl_y’, options=[{‘label’: i, ‘value’: i} for i in names], value=’petal-width’, style={‘width’:’50%’} ), ],style={‘width’:’100%’,’display’:’inline-block’}), html.Div([ dcc.Graph(id=’graph1') ],style={‘width’:’100%’,’display’:’inline-block’}) ] ) @app.callback( Output(component_id=’graph1', component_property=’figure’), [ Input(component_id=’ddl_x’, component_property=’value’), Input(component_id=’ddl_y’, component_property=’value’) ] ) def update_output(ddl_x_value, ddl_y_value): figure={ ‘data’: [ go.Scatter( x=data[data[‘class’] == cls][ddl_x_value], y=data[data[‘class’] == cls][ddl_y_value], mode=’markers’, marker={ ‘size’: 15 }, name=cls ) for cls in data[‘class’].unique() ], ‘layout’: [ go.Layout( height= 350, hovermode= ‘closest’, title=go.layout.Title(text=’Dash Interactive Data Visualization’,xref=’paper’, x=0) ) ] } return figure if __name__ == ‘__main__’: app.run_server(debug=True, port=8080)
代碼結構與前一個完全相同。初始化應用程序后,
- 添加了兩行數據讀取。
- 在app.layout部分中,添加了兩個下拉列表,並使用數據列循環填充選項。
- 在@ app.callback decorator中,將這兩個下拉列表添加為輸入組件
- 在update_output函數中,繪制一個散點圖,其中包含下拉列表選擇的數據和列。這里有一個棘手的部分。繪制每個類的散點圖。在go.Scatter()函數的末尾和'data'列表中有一個for循環。這個for循環(也稱為列表推導)返回Scatter()對象n次,其中n是數據“類”列中唯一記錄的數量。以下行是圖表的布局屬性。
代碼已准備好運行。
- 將其保存到擴展名為.py的文件中, - > “c:\…\dash_test.py”
- 使用python - > python “c:\…\dash_test.py”通過命令提示符調用它
- 打開瀏覽器並導航到應用程序 - >http://localhost:8080/