Dash应用布局
后续的操作前,需要安装如下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应用包括两个部分,应用布局(layout)和数据交互(interactivity)。其中布局部分用来展示数据以及引导使用者使用。Dash提供了dash_core_components
和dash_html_components
, 以类的方式对HTML和JS进行封装,便于调用。下面先构建一个最简单的布局
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()
创建了Dash应用的实例,这个实例可以通过app.run_server()
运行。
其次这个应用的布局(layout)由html组件(html.Div等)和图形组件(dcc.Graph等)构成。其中基础的html标签来自于dash_html_components
,而更加React.js库里的高级组件则是由dash_core_components
提供。
最后的展示形式需要后期慢慢的调整, 比如说调整一下字体对齐, 字体颜色和背景颜色等
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组件都设置了style
,用来调整样式,
可视化
dash_core_components
库中有一个Graph
组件,它利用开源的JavaScript图形库--plotly.js
进行交互式数据渲染。Graph里的figure
参数等价于plotly.py
里的figure
参数,即任何plotly.js
支持的图形都可以用dash_core_components
调用。查看https://plot.ly/python/了解更多plotly.py
的图形。
比如说这里可以基于Pandas的数据库创建散点图
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_components
得Markdown
提供了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进一步了解
小节
这部分主要是学习了Dash应用得layout
. layout
是不同组件的层级关系树,最后结果是html页面。html页面的HTML基本语法由dash_html_components
提供,而高级的绘图和下拉栏等则是由dash_core_components
提供.
参考资料:
- https://plot.ly/dash/getting-started
- https://plot.ly/dash/dash-core-components
- https://plot.ly/dash/dash-html-components