Python的Web可視化框架Dash(3)---布局

【Dash系列】Python的Web可視化框架Dash(1)---簡介
【Dash系列】Python的Web可視化框架Dash(2)---安裝
【Dash系列】Python的Web可視化框架Dash(3)---布局設(shè)置
【Dash系列】Python的Web可視化框架Dash(4)---基本回調(diào)
【Dash系列】Python的Web可視化框架Dash(5)---狀態(tài)和預(yù)更新
【Dash系列】Python的Web可視化框架Dash(6)---交互和過濾
【Dash系列】Python的Web可視化框架Dash(7)---回調(diào)共享
【Dash系列】Python的Web可視化框架Dash(8)---核心組件

本節(jié)通過6個獨(dú)立的示例,介紹Dash應(yīng)用程序的基本使用方法



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

Dash為應(yīng)用程序的所有可視化組件,提供了Python類,在dash_core_components庫和dash_html_components庫中,進(jìn)行組件的維護(hù)。當(dāng)然,也可以使用 JavaScript 和 React.js 構(gòu)建自己的組件。

導(dǎo)入本章所有用到的包,下文不再說明

import pandas as pd
import plotly.graph_objs as go
import dash
import dash_core_components as dcc                  # 交互式組件
import dash_html_components as html                 # 代碼轉(zhuǎn)html
from dash.dependencies import Input, Output         # 回調(diào)
from jupyter_plotly_dash import JupyterDash         # Jupyter中的Dash,如有疑問,見系列文章第2篇【安裝】


一、第一個Dash

(一) 代碼

app = JupyterDash('Hello Dash', )
app.layout = html.Div(
    children = [
        html.H1('你好,Dash'),
        html.Div('''Dash: Python網(wǎng)絡(luò)應(yīng)用框架'''),
        dcc.Graph(
            id='example-graph',
            figure = dict(
                data = [{'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': '北京'},
                        {'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name': '上海'}],
                layout = dict(title = 'Dash數(shù)據(jù)可視化')
            )
        )
    ]
)

app

(二) 效果圖

(三) 說明

  1. 布局 layouthtml.Divdcc.Graph 這樣的組件樹組成;

  2. Dash是 聲明式 的,通過關(guān)鍵字參數(shù)描述組件。即Dash主要通過屬性描述應(yīng)用,如 style、className、id等;

  3. dash_html_components 庫為每個HTML標(biāo)簽都提供了對應(yīng)的組件。本例中:html.H1(children='Hello Dash')可以生成<h1>你好,Dash</h1>這樣的HTML語句。并非所有組件都使用純HTML語言;

  4. dash_core_components 這種交互式高階組件庫,是由JavaScript、HTML和CSS編寫,并由React.js庫生成,用于設(shè)置互動性圖表組件,如控件、圖形等,其語法類似Plotly;

  5. 按照慣例,children 始終是第一個屬性,可以省略,即 html.H1(children='Hello Dash')html.H1('Hello Dash')相同,本例中,聲明了3次,實(shí)際上都可以忽略。另外,它還可以包含字符串、數(shù)字、單個組件或組件列表。

二、自定義HTML文本樣式

(一) 代碼

app = JupyterDash('Hello Dash Style')
colors = dict(background = '#111111', text = '#7FDBFF')

app.layout = html.Div(
    style = dict(backgroundColor = colors['background']),
    children = [
        html.H1(
            children='你好,Dash',
            style = dict(textAlign = 'center', color = colors['text'])),
        html.Div(
            children='Dash:Python網(wǎng)絡(luò)應(yīng)用框架',
            style = dict(textAlign = 'center', color = colors['text'])),
        dcc.Graph(
            id='example-graph-2',
            figure = dict(
                data = [{'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': '北京'},
                        {'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name': '天津'}],
                layout = dict(
                    plot_bgcolor = colors['background'], 
                    paper_bgcolor = colors['background'],
                    font = dict(color = colors['text'])
                )
            )
        )
    ]
)

app

(二) 效果圖

(三) 說明

  1. dash_html_components 庫除了為HTML參數(shù)提供了關(guān)鍵字外,還為每個HTML標(biāo)簽提供了組件類;
  2. 示例中,使用 style 屬性修改了 html.Divhtml.H1components 行內(nèi)樣式;
  3. dash_html_componentsHTML 屬性,與 HTML 屬性之間存以下幾點(diǎn)差異:
  • HTML中的style屬性是以分號分隔的字符串;Dash用的是字典;
  • Dash的style字典鍵是 camelCased(駝峰式) 命名法,HTML 中的 text-align,在style字典中為 textAlign
  • HTMLclass 屬性,對應(yīng)Dash中的 className
  • HTML 的子項(xiàng)是通過 children關(guān)鍵字參數(shù)指定的,按照慣例,這始終是第一個參數(shù),經(jīng)常被省略;
  • 除了上述外,其他所有HTML屬性與標(biāo)簽,在Python中都有效。

三、可重復(fù)使用的組件

(一) 代碼

# 數(shù)據(jù)源:美國農(nóng)業(yè)出口(2011年)
df = pd.read_csv(
    'https://gist.githubusercontent.com/chriddyp/'
    'c78bf172206ce24f77d6363a2d754b59/raw/'
    'c353e8ef842413cae56ae3920b8fd78468aa4cb2/'
    'usa-agricultural-exports-2011.csv')

# 定義表格組件
def create_table(df, max_rows=12):
    """基于dataframe,設(shè)置表格格式"""
    
    table = html.Table(
        # Header
        [
            html.Tr(
                [
                    html.Th(col) for col in df.columns
                ]
            )
        ] +
        # Body
        [
            html.Tr(
                [
                    html.Td(
                        df.iloc[i][col]
                    ) for col in df.columns
                ]
            ) for i in range(min(len(df), max_rows))
        ]   
    )
    return table

# 設(shè)置Dash應(yīng)用程序
app = JupyterDash('Defining Components')
app.layout = html.Div(
    children = [
        html.H4(children = '美國農(nóng)業(yè)出口數(shù)據(jù)表(2011年)'),
        create_table(df)
    ]
)
app

(二) 效果圖

(三) 說明

  1. 在Python中定義方法,Dash通過調(diào)用,可以創(chuàng)建復(fù)雜的可重用組件,如表格等,無需切換上下文或語言;
  2. 本示例實(shí)現(xiàn)的功能,是從Pandas的數(shù)據(jù)幀生成“表格”。

四、可視化散點(diǎn)圖

(一) 代碼

# 數(shù)據(jù)源
df = pd.read_csv(
    'https://gist.githubusercontent.com/chriddyp/' +
    '5d1ea79569ed194d432e56108a04d188/raw/' +
    'a9f9e8076b837d541398e999dcbac2b2826a81f8/'+
    'gdp-life-exp-2007.csv')

app = JupyterDash('Scatter Plot')
app.layout = html.Div([
    dcc.Graph(
        id = 'life-exp-vs-gdp',
        figure = dict(
            data = [
                go.Scatter(
                    x = df[df['continent'] == i]['gdp per capita'],
                    y = df[df['continent'] == i]['life expectancy'],
                    text = df[df['continent'] == i]['country'],
                    name = i,
                    mode = 'markers',
                    opacity = 0.8,
                    marker = dict(size = 15, line = dict(width = 0.5, color = 'white'))  
                ) for i in df.continent.unique()],
            layout = go.Layout(
                xaxis = dict(type = 'log', title = 'GDP Per Capita'),
                yaxis = dict(title = 'Life Expectancy'),
                margin = {'l': 40, 'b': 40, 't': 10, 'r': 10},
                legend = dict(x = 0, y = 1),
                hovermode = 'closest'
            )  
        )
    )
])

app

(二) 效果圖

(三) 說明

  1. dash_core_components 庫包含一個名為的組件Graph,其使用開源JavaScript圖形庫plotly.js ,呈現(xiàn)交互式數(shù)據(jù)可視化;
  2. Plotly.js 支持超過35種圖表類型,并以矢量質(zhì)量SVG和高性能WebGL的方式呈現(xiàn)圖表;
  3. dash_core_components.Graph 組件的參數(shù) figure ,與開放源碼的 Python 圖形庫 Plotly 中的參數(shù) figure使用方法,都是一樣的;
  4. 這些圖表具有互動性和響應(yīng)性:
  • 將鼠標(biāo)懸停在點(diǎn)上以查看其值;
  • 單擊圖例項(xiàng)以切換軌跡;
  • 單擊并拖動以縮放;
  • 按住shift后單擊并拖動,可以平移圖表;

五、Markdown文本

(一) 代碼

app = JupyterDash('Markdown')
text_notes = '''
### Dash和Markdown
Dash應(yīng)用程序可以用Markdown編寫。Dash使用 Markdown 的CommonMark規(guī)范。

如果這是你對Markdown的第一次介紹,請查看他們的[60 Second Markdown Tutorial](http://commonmark.org/help/)!
'''

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

app

(二) 效果圖

(三) 說明

  1. 雖然Dash通過 dash_html_components 庫可以實(shí)現(xiàn)文本編寫,但在HTML中編寫文本,比較繁瑣,需要寫入大量的格式化文本,推薦使用庫中的Markdown組件;
  2. Dash使用 MarkdownCommonMark規(guī)范;

六、核心組件

(一) 代碼

app = JupyterDash('Core Components')
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': '上海'}],
        value=['北京', '上海']),
    
    html.Label('Text Input'),
    dcc.Input(value = '天津', type = 'text'),
    
    html.Label('文本輸入'),
    dcc.Slider(
        min = 0, max = 9, value = 5,
        marks = {i: '標(biāo)簽 {}'.format(i) if i == 1 else str(i) for i in range(1, 6)})
],style={'columnCount': 2})

app

(二) 效果圖

(三) 說明

  1. 本示例中,展示了下拉列表單選、下拉列表多選、單選按鈕、多選按鈕、文本輸入框、滑動條;
  2. dash_core_components 包含一系列高級別的組件,如下拉列表、圖形、Markdown文本等;
  3. 與所有Dash組件一樣,這些組件都是聲明式的,組件的關(guān)鍵字參數(shù)也一樣,每個選項(xiàng)都可以進(jìn)行配置;
  4. Dash核心組件庫中,可以查看所有可用的組件。

七、小結(jié)

  1. Dash組件是聲明式的,在實(shí)例化關(guān)鍵字參數(shù)時,可設(shè)置配置項(xiàng)。通過調(diào)用help,可以查看Dash組件及其可用參數(shù)的更多信息;
help(dcc.Dropdown)
  1. 總結(jié)
  • 布局(layout)用來設(shè)置Dash應(yīng)用程序的樣式,是結(jié)構(gòu)化的樹狀組件;
  • dash_html_components 庫提供了所有的HTML標(biāo)簽和關(guān)鍵字參數(shù),用來設(shè)置HTML屬性,如style、className、id等;
  • dash_core_components 庫生成了更高級別的組件,如控件和圖形;
  • 具體參考官方文檔:dash_core_componentsdash_html_components
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。