天天看點

Dash與Plotly開發Web端互動式可視化應用

Dash與Plotly開發Web端互動式可視化應用

作者 | 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"      
Dash與Plotly開發Web端互動式可視化應用

現在可以打開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\')

 ]

)      

儲存檔案時,将在控制台視窗中看到一個帶有新調試器引腳的新行。如果代碼中存在問題,将看到錯誤消息。在這種情況下,需要再次調用該檔案并重新整理浏覽器。

Dash與Plotly開發Web端互動式可視化應用

現在為插入的元素添加一些樣式。可以使用樣式屬性接受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值。結果是浏覽器中的互動式條形圖。

Dash與Plotly開發Web端互動式可視化應用

更複雜一些

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

Dash與Plotly開發Web端互動式可視化應用

它太快了嗎?好吧看看代碼。

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/