使用Dash開發(fā)交互式數(shù)據(jù)可視化網(wǎng)頁--頁面布局

Dash應(yīng)用布局

后續(xù)的操作前,需要安裝如下Python包

pip install dash==0.20.0  # The core dash backend
pip install dash-renderer==0.11.2  # The dash front-end
pip install dash-html-components==0.8.0  # HTML components
pip install dash-core-components==0.18.1  # Supercharged components
pip install plotly --upgrade  # Plotly graphing library used in examples

使用Dash生成HTML

Dash應(yīng)用包括兩個部分,應(yīng)用布局(layout)和數(shù)據(jù)交互(interactivity)。其中布局部分用來展示數(shù)據(jù)以及引導(dǎo)使用者使用。Dash提供了dash_core_componentsdash_html_components, 以類的方式對HTML和JS進(jìn)行封裝,便于調(diào)用。下面先構(gòu)建一個最簡單的布局

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: A web application frameworkd for Python.
        '''),
    dcc.Graph(
        id = 'example-graph',
        figure = {
            'dash':[
                {'x': [1,2,3], 'y':[4,1,2], 'type':'bar', 'name':'SF'},
                {'x': [1,2,3], 'y':[2,4,5], 'type':'bar', 'name':'Montrel'},
                ],
            'layout':{
                'title':'Dash data Visualization'
                }
            }
        )
])

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

首先用app=dash.Dash()創(chuàng)建了Dash應(yīng)用的實例,這個實例可以通過app.run_server()運行。

其次這個應(yīng)用的布局(layout)由html組件(html.Div等)和圖形組件(dcc.Graph等)構(gòu)成。其中基礎(chǔ)的html標(biāo)簽來自于dash_html_components,而更加React.js庫里的高級組件則是由dash_core_components提供。

最后的展示形式需要后期慢慢的調(diào)整, 比如說調(diào)整一下字體對齊, 字體顏色和背景顏色等

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 = 'Hello Dash',
        style = {
            'textAlign':'center',
            'color': colors['text']
            }
        ),
    html.Div(children = '''
        Dash: A web application frameworkd for Python.
        ''', style = {
            'textAlign':'center',
            'color': colors['text']
            }
        ),
    dcc.Graph(
        id = 'example-graph',
        figure = {
            'data':[
                {'x': [1,2,3], 'y':[4,1,2], 'type':'bar', 'name':'SF'},
                {'x': [1,2,3], 'y':[2,4,5], 'type':'bar', 'name':'Montreal'},
                ],
            'layout':{
                'plot_bgcolor': colors['background'],
                'paper_bgcolor': colors['background'],
                'font':{
                    'color': colors['text']
                    },
                'title':'Dash data Visualization'
                }
            }
        )
])

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

這里的html組件都設(shè)置了style,用來調(diào)整樣式,

可視化

dash_core_components庫中有一個Graph組件,它利用開源的JavaScript圖形庫--plotly.js進(jìn)行交互式數(shù)據(jù)渲染。Graph里的figure參數(shù)等價于plotly.py里的figure參數(shù),即任何plotly.js支持的圖形都可以用dash_core_components調(diào)用。查看https://plot.ly/python/了解更多plotly.py的圖形。

比如說這里可以基于Pandas的數(shù)據(jù)庫創(chuàng)建散點圖

import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
import pandas as pd

app = dash.Dash()

df = pd.read_csv(
    'https://gist.githubusercontent.com/chriddyp/' +
    '5d1ea79569ed194d432e56108a04d188/raw/' +
    'a9f9e8076b837d541398e999dcbac2b2826a81f8/'+
    'gdp-life-exp-2007.csv')

plot = [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'
            )
        }
    )]

app.layout = html.Div(
    html.Div(children=[
        html.Div(className='col-md-4'),
        html.Div(plot,className='col-md-4')],
        className='row'
    )
)

# Append an externally hosted CSS stylesheet
my_css_url = "https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css"
app.css.append_css({
    "external_url": my_css_url
})

# Append an externally hosted JS bundle
my_js_url = 'https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js'
app.scripts.append_script({
    "external_url": my_js_url
})

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

這部分代碼將圖形部分的代碼從html組件中抽離出來,寫完之后,再添加到html總體組件中。此外還增加了bootstrap的css樣式。

Markdown語法

Dash的dash_html_components支持原生的HTML語句,而dash_core_componentsMarkdown提供了Markdown得渲染。

import dash
import dash_core_components as dcc
import dash_html_components as html

app = dash.Dash()

markdown_text = '''
### Dash and Markdown

Dash apps can be written in Markdown.
Dash uses the [CommonMark](http://commonmark.org/)
specification of Markdown.
Check out their [60 Second Markdown Tutorial](http://commonmark.org/help/)
if this is your first introduction to Markdown!
'''

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

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

dash_core_components里不僅僅提供了Markdown, graphs這些圖形組件,還支持下拉欄等其他使用工具,可在https://plot.ly/dash/dash-core-components進(jìn)一步了解

小節(jié)

這部分主要是學(xué)習(xí)了Dash應(yīng)用得layout. layout是不同組件的層級關(guān)系樹,最后結(jié)果是html頁面。html頁面的HTML基本語法由dash_html_components提供,而高級的繪圖和下拉欄等則是由dash_core_components提供.

參考資料:

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

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

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