【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é)介紹Dash應(yīng)用的常用核心組件,導(dǎo)入本節(jié)用到的所有包
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
一、下拉列表
(一) 默認下拉列表
沒有任何額外屬性的默認下拉列表的示例
-
代碼
app = JupyterDash('dropdown01', height = 120)
app.layout = html.Div([
dcc.Dropdown(
id = 'my_dropdown',
options = [{'label': '北京', 'value': '北京'},
{'label': '上海', 'value': '上海'},
{'label': '深圳', 'value': '深圳'}],
value = '北京'),
html.Div(id = 'output-01')
])
@app.callback(Output('output-01', 'children'), [Input('my_dropdown', 'value')])
def update_output(value):
return f"您已經(jīng)選擇:【{value}】"
app
-
效果圖
(二) 多值下拉列表
multi 屬性設(shè)置為True時,允許用戶一次選擇多個值
-
代碼
app = JupyterDash('dropdown01', height = 120)
app.layout = html.Div([
dcc.Dropdown(
id = 'my_dropdown',
options = [{'label': '北京', 'value': '北京'},
{'label': '上海', 'value': '上海'},
{'label': '深圳', 'value': '深圳'}],
value = ['北京', '上海'],
multi = True),
html.Div(id = 'output-01')
])
@app.callback(Output('output-01', 'children'), [Input('my_dropdown', 'value')])
def update_output(value):
return f"您已經(jīng)選擇:【{'、'.join([val for val in value])}】"
app
-
效果圖
(三) 禁用搜索
searchable 屬性,設(shè)置是否允許在下拉列表中搜索,默認為True,若要禁止搜索則需要設(shè)置為False。
-
代碼
app = JupyterDash('dropdown01', height = 120)
app.layout = html.Div([
dcc.Dropdown(
id = 'my_dropdown',
options = [{'label': '北京', 'value': '北京'},
{'label': '上海', 'value': '上海'},
{'label': '深圳', 'value': '深圳'}],
searchable=False),
html.Div(id = 'output-01')
])
@app.callback(Output('output-01', 'children'), [Input('my_dropdown', 'value')])
def update_output(value):
pass
app
-
效果圖
(四) 下拉清除
clearable 屬性,設(shè)置是否可以清空下拉按鈕的選值,默認為True,若要禁止清空則需要設(shè)置為False。
-
代碼
app = JupyterDash('dropdown01', height = 120)
app.layout = html.Div([
dcc.Dropdown(
id = 'my_dropdown',
options = [{'label': '北京', 'value': '北京'},
{'label': '上海', 'value': '上海'},
{'label': '深圳', 'value': '深圳'}],
value = '北京',
clearable = False),
html.Div(id = 'output-01')
])
@app.callback(Output('output-01', 'children'), [Input('my_dropdown', 'value')])
def update_output(value):
return f"您已經(jīng)選擇:【{value}】"
app
-
效果圖
(五) 占位符文本
placeholder 屬性,設(shè)置未選擇任何值時,顯示的默認文本。
-
代碼
app = JupyterDash('dropdown01', height = 120)
app.layout = html.Div([
dcc.Dropdown(
id = 'my_dropdown',
options = [{'label': '北京', 'value': '北京'},
{'label': '上海', 'value': '上海'},
{'label': '深圳', 'value': '深圳'}],
placeholder = '選擇一個城市名稱'),
html.Div(id = 'output-01')
])
@app.callback(Output('output-01', 'children'), [Input('my_dropdown', 'value')])
def update_output(value):
pass
app
-
效果圖
(六) 禁用下拉列表
通過設(shè)置 disabled=True 可以禁止選取下拉列表。
-
代碼
app = JupyterDash('dropdown01', height = 120)
app.layout = html.Div([
dcc.Dropdown(
id = 'my_dropdown',
options = [{'label': '北京', 'value': '北京'},
{'label': '上海', 'value': '上海'},
{'label': '深圳', 'value': '深圳'}],
disabled = True),
html.Div(id = 'output-01')
])
@app.callback(Output('output-01', 'children'), [Input('my_dropdown', 'value')])
def update_output(value):
pass
app
-
效果圖
(七) 禁用選項
在下拉菜單中,禁用特定的選項,需要在 options 屬性下,設(shè)置 disabled = True。
-
代碼
app = JupyterDash('dropdown01', height = 150)
app.layout = html.Div([
dcc.Dropdown(
id = 'my_dropdown',
options = [{'label': '北京', 'value': '北京'},
{'label': '上海', 'value': '上海', 'disabled': True},
{'label': '深圳', 'value': '深圳'}],
value = '北京'),
html.Div(id = 'output-01')
])
@app.callback(Output('output-01', 'children'), [Input('my_dropdown', 'value')])
def update_output(value):
return f"您已經(jīng)選擇:【{value}】"
app
-
效果圖
二、滑塊
(一) 簡單的滑塊
綁定到回調(diào)的基本滑塊的示例
-
代碼
app = JupyterDash('slider', height = 120)
app.layout = html.Div([
dcc.Slider(
id = 'my-slider',
min = 0,
max = 20,
step = 0.5,
value = 10),
html.Div(id = 'slider-output-container')
])
@app.callback(Output('slider-output-container', 'children'), [Input('my-slider', 'value')])
def update_output(value):
return f"你已選擇到:{value}"
app
-
效果圖
(二) 標記和步驟
屬性 marks ,字典類型,dict鍵為滑塊的值、dict值為滑塊的標簽。如果用屬性 marks 進行定義滑塊,則必須將屬性 step 設(shè)置為 None,否則仍然會按默認的 step = 1 進行滑動。
-
代碼
app = JupyterDash('slider', height = 120)
app.layout = html.Div([
dcc.Slider(
min = 0,
max = 10,
step = None,
marks = {0: '0 °F', 3: '3 °F', 5: '5 °F', 7.65: '7.65 °F', 10: '10 °F'},
value = 7.65
)],
style = dict(padding = '5px'),
)
app
-
效果圖
(三) 滑塊突顯和標記風(fēng)格
默認情況下 included=True,表示突出顯示選擇的滑塊區(qū)間。marks 屬性下的子屬性 style 可以設(shè)置標記風(fēng)格。
-
代碼
app = JupyterDash('slider', height = 120)
app.add_external_link = False
app.layout = html.Div([
dcc.Slider(
min = 0,
max = 100,
value = 65,
included=False,
marks = {
0: {'label': '0 °C', 'style': {'color': '#77b0b1'}},
26: {'label': '26 °C'},
37: {'label': '37 °C'},
100: {'label': '100 °C', 'style': {'color': '#f50'}}
})],
style = dict(padding = '5px')
)
app
-
效果圖
(四) 非線性滑塊和更新模式
設(shè)置 marks 屬性的標簽為對數(shù),在回調(diào)中調(diào)整滑塊的輸出值,創(chuàng)建對數(shù)滑塊。屬性updatemode,為drag時表示每次移動句柄時都會觸發(fā)回調(diào),默認為mouseup,表示滑塊釋放鼠標時觸發(fā)回調(diào)。
-
代碼
app = JupyterDash('slider', height = 120)
app.add_external_link = False
app.layout = html.Div([
dcc.Slider(
id = 'slider-updatemode',
max = 3,
step = 0.01,
value = 2,
updatemode = 'drag',
marks = {i: f"{str(10 ** i)}" for i in range(4)}),
html.Div(id = 'updatemode-output-container', style = dict(marginTop = 20,))],
style = dict(padding = '5px'))
@app.callback(Output('updatemode-output-container', 'children'), [Input('slider-updatemode', 'value')])
def display_value(value):
return f"線性值:{value} | 對數(shù)值:{value ** 10}"
app
-
效果圖
三、范圍滑塊
(一) 簡單的RangeSlider
綁定到回調(diào)的基本RangeSlider的示例
-
代碼
app = JupyterDash('range_slider', height = 120)
app.add_external_link = False
app.layout = html.Div([
dcc.RangeSlider(
id = 'my-range-slider',
min = 0,
max = 20,
step = 0.5,
value = [5, 15]),
html.Div(id = 'output-container-range-slider')
])
@app.callback(Output('output-container-range-slider', 'children'), [Input('my-range-slider', 'value')])
def update_output(value):
return f"你選擇的范圍:{value}"
app
-
效果圖
(二) 標記和步驟
marks定義了滑塊,并將step其設(shè)置為None,滑塊將只能選擇已由其預(yù)定義的值marks。
-
代碼
app = JupyterDash('range_slider', height = 120)
app.add_external_link = False
app.layout = html.Div([
dcc.RangeSlider(
min = 0,
max = 10,
step = None,
marks = {0: '0 °F', 3: '3 °F', 5: '5 °F', 7.65: '7.65 °F', 10: '10 °F'},
value = [3, 7.65]
)],
style = dict(padding = '5px'),
)
app
-
效果圖
(三) 標記和步驟
marks定義了滑塊,并將step其設(shè)置為None,滑塊將只能選擇已由其預(yù)定義的值marks。
-
代碼
app = JupyterDash('range_slider', height = 120)
app.add_external_link = False
app.layout = html.Div([
dcc.RangeSlider(
min = 0,
max = 100,
value = [10, 65],
included=False,
marks = {
0: {'label': '0 °C', 'style': {'color': '#77b0b1'}},
26: {'label': '26 °C'},
37: {'label': '37 °C'},
100: {'label': '100 °C', 'style': {'color': '#f50'}}
})],
style = dict(padding = '5px')
)
app
-
效果圖
(四) 多手柄
要創(chuàng)建多個手柄,只需為其定義更多值value
-
代碼
app = JupyterDash('range_slider', height = 120)
app.add_external_link = False
app.layout = html.Div([
dcc.RangeSlider(
min=0,
max=30,
value=[1, 3, 4, 5, 12, 17])],
style = dict(padding = '5px')
)
app
-
效果圖
(五) 可推動手柄
屬性pushable屬性可以是數(shù)值,也可以是布爾值。數(shù)值確定手柄之間的最小距離
-
代碼
app = JupyterDash('range_slider', height = 120)
app.add_external_link = False
app.layout = html.Div([
dcc.RangeSlider(
min=0,
max=30,
value=[8, 10, 15, 17, 20],
pushable=2)],
style = dict(padding = '5px')
)
app
-
效果圖
(六) 穿越手柄
如果allowCross=False,手柄將不允許相互交叉
-
代碼
app = JupyterDash('range_slider', height = 120)
app.add_external_link = False
app.layout = html.Div([
dcc.RangeSlider(
min=0,
max=30,
value=[10, 15],
allowCross=False)],
style = dict(padding = '5px')
)
app
-
效果圖
四、輸入框
(一) 支持的輸入類型
-
代碼
app = JupyterDash('input', height = 120)
app.add_external_link = False
allowed_types = ("text", "number", "password", "email", "search", "tel", "url", "range", "hidden")
app.layout = html.Div([
dcc.Input(
id = f"input_{t}",
type = t,
placeholder = f"input type {t}") for t in allowed_types]
+ [html.Div(id="out-all-types")])
@app.callback(Output("out-all-types", "children"), [Input(f"input_{t}", "value") for t in allowed_types])
def cb_render(*vals):
return ' ~~ '.join((str(val) for val in vals if val))
app
-
效果圖
(二) 延遲顯示輸入的內(nèi)容
-
代碼
app = JupyterDash('input', height = 150)
app.add_external_link = False
app.layout = html.Div([
html.I('嘗試分別在兩個輸入框中輸入數(shù)據(jù),觀察回調(diào)中如何延遲顯示'),
html.Br(),
html.Br(),
html.I('第2個輸入框輸入內(nèi)容后,按下Enter鍵或鼠標點擊非操作區(qū),即可顯示內(nèi)容'),
html.Br(),
html.Br(),
dcc.Input(id = 'input1', type = 'text', placeholder = '北京'),
dcc.Input(id = 'input2', type = 'text', placeholder = '上海', debounce=True),
html.Div(id = 'output')
])
@app.callback(Output("output", "children"), [Input("input1", "value"), Input("input2", "value")])
def update_output(input1, input2):
return f"輸入框 1 輸出:{input1},輸入框 2 輸出:{input2}"
app
-
效果圖
(三) 數(shù)字輸入
設(shè)置 type 為 number時,僅接受輸入整型數(shù)字(Integer),若需要輸入 Float 時,需要在回調(diào)函數(shù)中額外添加。
-
代碼
app = JupyterDash('input', height = 150)
app.add_external_link = False
app.layout = html.Div([
dcc.Input(id = 'df', type = 'number', placeholder = '不延遲顯示'),
dcc.Input(id = 'dt', type = 'number', debounce = True, placeholder = '延遲顯示'),
dcc.Input(id = 'range', type = 'number', placeholder = '范圍', min = 10, max = 100, step = 5),
html.Hr(),
html.Div(id = 'number-out')
])
@app.callback(Output('number-out', 'children'), [Input('df', 'value'), Input('dt', 'value'), Input('range', 'value')])
def number_render(fval, tval, rangeval):
return f"方框1: {fval}, 方框2: {tval}, 方框3: {rangeval}"
app
-
效果圖
五、選項卡
(一) 內(nèi)容作為回調(diào)
將圖表的內(nèi)容通過回調(diào),添加到Tab組件的children 屬性中
-
代碼
app = JupyterDash('input', height = 600)
app.add_external_link = False
app.layout = html.Div([
html.H2('選項卡示例', style = dict(textAlign='center')),
dcc.Tabs(
id = 'tabs-example',
value = 'tab-1',
children = [dcc.Tab(label = '選項卡一', value = 'tab-1'),
dcc.Tab(label = '選項卡二', value = 'tab-2')]),
html.Div(id = 'tabs-demo')
])
@app.callback(Output('tabs-demo', 'children'), [Input('tabs-example', 'value')])
def render_content(tab):
if tab == 'tab-1':
return html.Div([
html.H3('內(nèi)容一'),
dcc.Graph(
id='graph-1-tabs',
figure = dict(data = [dict(x = [1, 2, 3], y = [3, 1, 2], type = 'bar')])
)
])
else:
return html.Div([
html.H3('內(nèi)容二'),
dcc.Graph(
id='graph-2-tabs',
figure = dict(data = [dict(x = [1, 2, 3], y = [5, 10, 6], type = 'bar')])
)
])
app
-
效果圖
(二) 內(nèi)容為Tab子項
可以直接將圖表的內(nèi)容,作為children屬性嵌入到Tab組件中
-
代碼
app = JupyterDash('input', height = 600)
app.add_external_link = False
app.layout = html.Div([
dcc.Tabs(id = 'tabs', children = [
dcc.Tab(label = 'tab-1', children = [
html.Div([dcc.Graph(
id = 'graph-1',
figure = dict(data = [dict(x = [1, 2, 3], y = [4, 1, 2], type = 'bar', name = 'users'),
dict(x = [1, 2, 3], y = [2, 4, 5], type = 'bar', name = 'orders')]))])]),
dcc.Tab(label = 'tab-2', children = [
html.Div([dcc.Graph(
id = 'graph-2',
figure = dict(data = [dict(x = [1, 2, 3], y = [1, 4, 1], type = 'bar', name = 'users'),
dict(x = [1, 2, 3], y = [1, 2, 3], type = 'bar', name = 'orders')]))])]),
dcc.Tab(label = 'tab-3', children = [
html.Div([dcc.Graph(
id = 'graph-3',
figure = dict(data = [dict(x = [1, 2, 3], y = [2, 4, 3], type = 'bar', name = 'users'),
dict(x = [1, 2, 3], y = [5, 4, 3], type = 'bar', name = 'orders')])
)])
]),
])
])
app
-
效果圖
六、其它常用組件
(一) 多行文本
-
代碼
app = JupyterDash('input', height = 150)
app.add_external_link = False
app.layout = html.Div([
dcc.Textarea(
placeholder='請輸入內(nèi)容...',
value='這是一個多行文本框的組件',
style={'width': '100%'})
])
app
-
效果圖
(二) 復(fù)選框
-
代碼
app = JupyterDash('input', height = 150)
app.add_external_link = False
app.layout = html.Div([
dcc.Checklist(
options=[{'label': '北京', 'value': 'BJ'},
{'label': '上海', 'value': 'SHH'},
{'label': '深圳', 'value': 'SZ'}],
value=['BJ', 'SZ']
)
])
app
-
效果圖
(三) 單選框
綁定到回調(diào)的基本RangeSlider的示例
-
代碼
app = JupyterDash('input', height = 150)
app.add_external_link = False
app.layout = html.Div([
dcc.RadioItems(
options=[{'label': '北京', 'value': 'BJ'},
{'label': '上海', 'value': 'SHH'},
{'label': '深圳', 'value': 'SZ'}],
value='BJ',
)
])
app
-
效果圖
(四) 按鈕
默認屬性n_clicks是一個整數(shù),表示點擊按鈕的次數(shù),默認值為None;屬性n_clicks_timestamp是整數(shù)時間戳,表示點擊按鈕的時間
-
代碼
app = JupyterDash('input', height = 120)
app.add_external_link = False
app.layout = html.Div([
html.Button('Buttons', id = 'button'),
html.Div(id = 'output-id')
])
@app.callback(Output('output-id', 'children'), [Input('button', 'n_clicks')])
def update_output(n_clicks):
n_clicks = 0 if not n_clicks else n_clicks
return f"你已點擊按鈕了{n_clicks}次"
app
-
效果圖
(五) 日期按鈕
參數(shù)display_format設(shè)置日期格式;參數(shù)month_format設(shè)置日歷中月格式;參數(shù)first_day_of_week設(shè)置周幾為周第一天;參數(shù)clearable設(shè)置是否可以清楚選擇
-
代碼
import arrow as ar
app = JupyterDash('input', height = 350)
app.add_external_link = False
app.layout = html.Div([
dcc.DatePickerSingle(
id='dt',
date='2019-06-01',
display_format = 'Y-MM-DD',
month_format = 'Y-MM',
first_day_of_week = 1,
min_date_allowed=ar.get(2019, 1, 1).date(),
max_date_allowed=ar.get(2019, 10, 1).date(),
clearable=True),
html.Div(id='output-dt')
])
@app.callback(Output('output-dt', 'children'), [Input('dt', 'date')])
def update_output(date):
str_prefix = '您已選擇 : ' if date else '暫無選擇'
str_dt = ar.get(date).format('YYYY-MM-DD') if date else ''
return str_prefix + str_dt
app
-
效果圖
(六) 日期范圍
-
代碼
import arrow as ar
app = JupyterDash('input', height = 350)
app.add_external_link = False
app.layout = html.Div([
dcc.DatePickerRange(
id='dt_range',
start_date=ar.get(2019, 1, 1).date(),
end_date_placeholder_text='選擇日期',
display_format = 'Y-MM-DD',
month_format = 'Y-MM',
first_day_of_week = 1,
min_date_allowed=ar.get(2010, 1, 1).date(),
max_date_allowed=ar.get(2020, 10, 1).date()
),
html.Div(id='output-dt')
])
app
-
效果圖
(七) Markdown
Markdown是一種編寫和格式化文本的簡單方法。它包括粗體文本和斜體, 鏈接,內(nèi)聯(lián)code
片段,列表,引號等語法。
-
代碼
app = JupyterDash('input', height = 350)
app.add_external_link = False
app.layout = html.Div([
dcc.Markdown('''
#### Dash and Markdown
Dash supports [Markdown](http://commonmark.org/help).
Markdown is a simple way to write and format text.
It includes a syntax for things like **bold text** and *italics*,
[links](http://commonmark.org/help), inline `code` snippets, lists,
quotes, and more.
''')
])
app
-
效果圖