交互性
后續(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
第一部分
完成了整體布局惦界,但是基本都是靜態(tài)圖形,無(wú)法體現(xiàn)dash交互性數(shù)據(jù)探索特性论衍。這一部分則是讓圖形能夠動(dòng)起來(lái)堰燎,對(duì)我們的操作有所回應(yīng)。
import dash
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html
app = dash.Dash()
app.layout = html.Div([
dcc.Input(id='my-id', value='initial vale', type='text'),
html.Div(id='my-div')
])
@app.callback(
Output(component_id='my-div', component_property='children'),
[Input(component_id='my-id', component_property='value')]
)
def update_output_div(input_value):
return 'you\'ve entered "{}"'.format(input_value)
if __name__=='__main__':
app.run_server()
運(yùn)行之后會(huì)的界面只有一個(gè)dcc.Input
提供的輸入框淆储,但是這個(gè)輸入框是輸入后修壕,是可以改變頁(yè)面中的文字。那么這個(gè)是如何實(shí)現(xiàn)的呢遏考?
我們的應(yīng)用界面的輸入和輸出是通過(guò)app.callback
裝飾器進(jìn)行聲明慈鸠。
在Dash中,應(yīng)用的輸入輸出其實(shí)就是某個(gè)組件的屬性(properties)灌具。因此青团,Output(component_id='my-div', component_property='children')
就可以解釋為,將值輸出到ID為my-div
的HTML組件的children
的參數(shù)中咖楣,而[Input(component_id='my-id', component_property='value')]
則表明輸入時(shí)來(lái)自于ID為my-id
的value
參數(shù)督笆。
隨著輸入的值的改變,裝飾器會(huì)調(diào)用函數(shù)update_output_div
生成新值诱贿。這其實(shí)有點(diǎn)像Excel娃肿,當(dāng)你寫(xiě)好一個(gè)函數(shù)后,修改原來(lái)值會(huì)產(chǎn)生新的值珠十,這種編程方法叫做"Reactive Programming"料扰,應(yīng)該可以翻譯為響應(yīng)式編程吧.
讓我們更進(jìn)一步,看看使用Slider
組件加上響應(yīng)式編程后焙蹭,圖片是如何動(dòng)起來(lái). 數(shù)據(jù)和之前使用的一致晒杈,之前是展示了所有年份,不同洲的國(guó)家的GDP分布情況孔厉。而這里則可以使用滑動(dò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
df = pd.read_csv(
'https://raw.githubusercontent.com/plotly/'
'datasets/master/gapminderDataFiveYear.csv')
app = dash.Dash()
app.layout = html.Div([
dcc.Graph(id = 'graph-with-slider'),
dcc.Slider(
id = 'years-slider',
min = df['year'].min(),
max = df['year'].max(),
value = df['year'].min(),
step = None,
marks = {str(year): str(year) for year in df['year'].unique()}
)
])
@app.callback(
dash.dependencies.Output(component_id = 'graph-with-slider', component_property = "figure"),
[dash.dependencies.Input('years-slider', 'value')]
)
def update_figure(selected_year):
filtered_df = df[df.year == selected_year]
traces = []
for i in filtered_df.continent.unique():
df_by_continent = filtered_df[filtered_df['continent'] == i]
traces.append(go.Scatter(
x = df_by_continent['gdpPercap'],
y = df_by_continent['lifeExp'],
text = df_by_continent['country'],
mode = 'markers',
opacity = 0.7,
marker = {
'size': 15,
'line': {'width':0.5, 'color':'white'}
},
name = i
))
return {
'data': traces,
'layout': go.Layout(
xaxis = {'type':'log', 'title':'GDP Per Capita'},
yaxis = {'title':'Life Expectancy', 'range':[20,90]},
margin = {'l':40, 'b':40, 't':10, 'r':10},
legend = {'x':0, 'y':1},
hovermode = 'closest'
)
}
if __name__ == '__main__':
app.run_server()
首先是在布局中設(shè)置了兩個(gè)占位組件撰豺,這兩個(gè)占位組件一個(gè)用于提供年份用于篩選粪般,一個(gè)用于則是展示輸出。然后update_figure
接受值返回對(duì)應(yīng)的圖形對(duì)象污桦,最后展示到瀏覽器中亩歹。
Dash應(yīng)用在啟動(dòng)的時(shí)候會(huì)加載數(shù)據(jù),因此當(dāng)用戶訪問(wèn)應(yīng)用的時(shí)候,數(shù)據(jù)已經(jīng)在內(nèi)存中捆憎,隨后用戶的交互操作就能得到及時(shí)的響應(yīng)舅柜。當(dāng)然callback
函數(shù)不會(huì)修改原始數(shù)據(jù),它僅僅是在內(nèi)存中創(chuàng)建新的拷貝而已躲惰。
多個(gè)輸入值
上一節(jié)只是單個(gè)輸入單個(gè)輸出致份,在Dash中,每個(gè)Output础拨,都可以由多個(gè)Input氮块。這一部分則是介紹通過(guò)加入更多調(diào)節(jié)組件多角度地展示數(shù)據(jù)。這里用到了五個(gè)調(diào)節(jié)組件诡宗,為2個(gè)Dropdown
, 2個(gè)RadioItems
和1個(gè)Slider
滔蝉。
import dash
from dash.dependencies import Input, Output
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/'
'cb5392c35661370d95f300086accea51/raw/'
'8e0768211f6b747c0db42a9ce9a0937dafcbd8b2/'
'indicators.csv')
available_indicators = df['Indicator Name'].unique()
app.layout = html.Div([
html.Div([
html.Div([
dcc.Dropdown(
id='xaxis-column',
options=[{'label':i, 'value':i} for i in available_indicators],
value = 'Fertility rate, total(births per woman)'
),
dcc.RadioItems(
id = 'xaxis-type',
options = [{'label':i, 'value':i} for i in ['Liner','Log']],
value = 'Liner',
labelStype={'display':'inline-block'}
)
],
style = {'width':'48%', 'display':'inline-block'}),
html.Div([
dcc.Dropdown(
id = 'yaxis-column',
options = [{'label':i, 'value':i} for i in available_indicators],
value = 'Life expectancy at birth, total(year)'
),
dcc.RadioItems(
id = 'yaxis-type',
options = [{'label':i, 'value':i} for i in ['Liner','Log']],
value = 'Liner',
labelStyle={'display':'inline-block'}
)
], style={'width':'48%','float':'right','display':'inline-block'})
]),
dcc.Graph(id='indicator-graphic'),
dcc.Slider(
id='year-slider',
min=df['Year'].min(),
max=df['Year'].max(),
value=df['Year'].max(),
step=None,
marks={str(year): str(year) for year in df['Year'].unique()}
)
])
@app.callback(
Output('indicator-graphic','figure'),
[Input('xaxis-column','value'),
Input('yaxis-column','value'),
Input('xaxis-type','value'),
Input('yaxis-type','value'),
Input('year-slider','value')
]
)
def update_graph(xaxis_column_name, yaxis_column_name,
xaxis_type, yaxis_type,
year_value):
dff = df[df['Year'] == year_value]
return {
'data':[go.Scatter(
x=dff[dff['Indicator Name'] == xaxis_column_name]['Value'],
y=dff[dff['Indicator Name'] == yaxis_column_name]['Value'],
text=dff[dff['Indicator Name'] == yaxis_column_name]['Country Name'],
mode = 'markers',
marker = {
'size': 15,
'opacity': 0.5,
'line':{'width':0.5, 'color':'white'}
}
)],
'layout':go.Layout(
xaxis={
'title':xaxis_column_name,
'type':'linear' if xaxis_type == 'Liner' else 'log'
},
yaxis={
'title': yaxis_column_name,
'type': 'linear' if yaxis_type == 'Liner' else 'log'
},
margin={'l':40, 'b':40,'t':10,'r':0},
hovermode='closest'
)
}
if __name__ == '__main__':
app.run_server()
和單個(gè)輸入?yún)^(qū)別不大,就是輸入多了塔沃,要寫(xiě)的代碼多了蝠引,寫(xiě)代碼的時(shí)候可能會(huì)寫(xiě)錯(cuò)而已。如果有多個(gè)輸出的需求蛀柴,只要定義多個(gè)callback
函數(shù)即可螃概。
第二部分小節(jié)
Dash應(yīng)用使用裝飾器callback
進(jìn)行響應(yīng)式編程「爰玻回調(diào)函數(shù)根據(jù)component_id
和component_property
從不同組件中獲取輸入值吊洼,然后其所裝飾的函數(shù)進(jìn)行計(jì)算后,將值返回裝飾器制肮,最后將計(jì)算結(jié)果輸出到指定組件中冒窍。