一、Dash简介
Dash是一个用于构建Web应用程序的高效Python框架。 Dash写在Flask,Plotly.js和React.js之上,在纯Python中,使用高度自定义的用户界面,构建数据可视化应用程序。 它特别适合使用Python进行数据分析的人。
Dash官网:https://dash.plotly.com
二、Dash安装
安装的包还是挺多的
(py_100) PS E:\python_100> pip install dash -i https://mirror.baidu.com/pypi/simple
Looking in indexes: https://mirror.baidu.com/pypi/simple
Collecting dash
Downloading https://mirror.baidu.com/pypi/packages/96/3f/f287d7a0084460e41abb636694a9dc13d030733687d944256fccdbac2ff8/dash-2.0.
0-py3-none-any.whl (7.3 MB)
|████████████████████████████████| 7.3 MB 2.2 MB/s
Collecting Flask>=1.0.4
Downloading https://mirror.baidu.com/pypi/packages/8f/b6/b4fdcb6d01ee20f9cfe81dcf9d3cd6c2f874b996f186f1c0b898c4a59c04/Flask-2.0
.2-py3-none-any.whl (95 kB)
|████████████████████████████████| 95 kB 1.9 MB/s
Collecting plotly>=5.0.0
Downloading https://mirror.baidu.com/pypi/packages/68/b2/7c7d111affebb281b1085680db7358f6204920bb5574e9e84db05c530688/plotly-5.
3.1-py2.py3-none-any.whl (23.9 MB)
|████████████████████████████████| 23.9 MB 6.4 MB/s
Collecting dash-core-components==2.0.0
Downloading https://mirror.baidu.com/pypi/packages/41/55/ad4a2cf9b7d4134779bd8d3a7e5b5f8cc757f421809e07c3e73bb374fdd7/dash_core
_components-2.0.0.tar.gz (3.4 kB)
Preparing metadata (setup.py) ... done
Collecting flask-compress
Downloading https://mirror.baidu.com/pypi/packages/75/fa/a3c96f3f367ad1d6532fa8394c9a6f5879513868207096f6b41f4168b342/Flask_Com
press-1.10.1-py3-none-any.whl (7.9 kB)
Collecting dash-table==5.0.0
Downloading https://mirror.baidu.com/pypi/packages/3a/81/34983fa0c67125d7fff9d55e5d1a065127bde7ca49ca32d04dedd55f9f35/dash_tabl
e-5.0.0.tar.gz (3.4 kB)
Preparing metadata (setup.py) ... done
Collecting dash-html-components==2.0.0
Downloading https://mirror.baidu.com/pypi/packages/14/c6/957d5e83b620473eb3c8557a253fb01c6a817b10ca43d3ff9d31796f32a6/dash_html
_components-2.0.0.tar.gz (3.8 kB)
Preparing metadata (setup.py) ... done
Collecting Werkzeug>=2.0
Downloading https://mirror.baidu.com/pypi/packages/1e/73/51137805d1b8d97367a8a77cae4a792af14bb7ce58fbd071af294c740cf0/Werkzeug-
2.0.2-py3-none-any.whl (288 kB)
|████████████████████████████████| 288 kB 6.4 MB/s
Collecting Jinja2>=3.0
Downloading https://mirror.baidu.com/pypi/packages/94/42/d8bca8e99789bcc35dfa9b03acaa8b518720d6e060163745bc2bf2ead842/Jinja2-3.
0.2-py3-none-any.whl (133 kB)
|████████████████████████████████| 133 kB ...
Collecting itsdangerous>=2.0
Downloading https://mirror.baidu.com/pypi/packages/9c/96/26f935afba9cd6140216da5add223a0c465b99d0f112b68a4ca426441019/itsdanger
ous-2.0.1-py3-none-any.whl (18 kB)
Collecting click>=7.1.2
Downloading https://mirror.baidu.com/pypi/packages/48/58/c8aa6a8e62cc75f39fee1092c45d6b6ba684122697d7ce7d53f64f98a129/click-8.0
.3-py3-none-any.whl (97 kB)
|████████████████████████████████| 97 kB ...
Collecting tenacity>=6.2.0
Downloading https://mirror.baidu.com/pypi/packages/f2/a5/f86bc8d67c979020438c8559cc70cfe3a1643fd160d35e09c9cca6a09189/tenacity-
8.0.1-py3-none-any.whl (24 kB)
Requirement already satisfied: six in e:\python_100\py_100\lib\site-packages (from plotly>=5.0.0->dash) (1.16.0)
Collecting brotli
Downloading https://mirror.baidu.com/pypi/packages/6b/11/7d28cd3a5492fed09159e9b37613fdcec7655d93dec664b79d4bb4bb67b8/Brotli-1.
0.9-cp310-cp310-win_amd64.whl (383 kB)
|████████████████████████████████| 383 kB 409 kB/s
Collecting colorama
Downloading https://mirror.baidu.com/pypi/packages/44/98/5b86278fbbf250d239ae0ecb724f8572af1c91f4a11edf4d36a206189440/colorama-
0.4.4-py2.py3-none-any.whl (16 kB)
Collecting MarkupSafe>=2.0
Downloading https://mirror.baidu.com/pypi/packages/93/28/d42b954fb9189cf4b78b0b0a025cff9b2583f93b37d1a345768ade29e5dd/MarkupSaf
e-2.0.1-cp310-cp310-win_amd64.whl (15 kB)
Using legacy 'setup.py install' for dash-core-components, since package 'wheel' is not installed.
Using legacy 'setup.py install' for dash-html-components, since package 'wheel' is not installed.
Using legacy 'setup.py install' for dash-table, since package 'wheel' is not installed.
Installing collected packages: MarkupSafe, colorama, Werkzeug, Jinja2, itsdangerous, click, tenacity, Flask, brotli, plotly, flas
k-compress, dash-table, dash-html-components, dash-core-components, dash
Running setup.py install for dash-table ... done
Running setup.py install for dash-html-components ... done
Running setup.py install for dash-core-components ... done
Successfully installed Flask-2.0.2 Jinja2-3.0.2 MarkupSafe-2.0.1 Werkzeug-2.0.2 brotli-1.0.9 click-8.0.3 colorama-0.4.4 dash-2.0.
0 dash-core-components-2.0.0 dash-html-components-2.0.0 dash-table-5.0.0 flask-compress-1.10.1 itsdangerous-2.0.1 plotly-5.3.1 te
nacity-8.0.1
三、Dash布局实例
Dash应用程序由两部分组成。第一部分是布局(layout),描述应用程序的设计样式;第二部分描述了应用程序的交互性。 Dash为应用程序的所有可视化组件,提供了Python类,在dash_core_components(dcc)库和dash_html_components(html)库中,进行组件的维护。
以下实例代码都是复制借鉴官网实例来的。 说明部分借鉴了简书一篇优秀文章: 作者:惑也 链接:https://www.jianshu.com/p/ca1b2ae4883e 来源:简书 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
3.1 实例1:柱状图
import dash
from dash import dcc
from dash import html
import plotly.express as px
import pandas as pd
app = dash.Dash(__name__)
df = pd.DataFrame({
"Fruit": ["Apples", "Oranges", "Bananas", "Apples", "Oranges", "Bananas"],
"Amount": [4, 1, 2, 2, 4, 5],
"City": ["SF", "SF", "SF", "Montreal", "Montreal", "Montreal"]
})
fig = px.bar(df, x="Fruit", y="Amount", color="City", barmode="group")
app.layout = html.Div(children=[
html.H1(children='Hello Dash'),
html.Div(children='''
Dash: A web application framework for your data.
'''),
dcc.Graph(
id='example-graph',
figure=fig
)
])
if __name__ == '__main__':
app.run_server(debug=True)
说明
布局 layout 由 html.Div 和 dcc.Graph 这样的组件树组成;
Dash是 声明式 的,通过关键字参数描述组件。即Dash主要通过属性描述应用,如 style、className、id等;
dash_html_components 库为每个HTML标签都提供了对应的组件。本例中:html.H1(children='Hello Dash')可以生成<h1>你好,Dash</h1>这样的HTML语句。并非所有组件都使用纯HTML语言;
dash_core_components 这种交互式高阶组件库,是由JavaScript、HTML和CSS编写,并由React.js库生成,用于设置互动性图表组件,如控件、图形等,其语法类似Plotly;
按照惯例,children 始终是第一个属性,可以省略,即 html.H1(children='Hello Dash') 和 html.H1('Hello Dash')相同,本例中,声明了3次,实际上都可以忽略。另外,它还可以包含字符串、数字、单个组件或组件列表。
3.2 实例2:自定义HTML文本样式
import dash
from dash import dcc
from dash import html
import plotly.express as px
import pandas as pd
app = dash.Dash(__name__)
colors = {
'background': '#111111',
'text': '#7FDBFF'
}
df = pd.DataFrame({
"Fruit": ["Apples", "Oranges", "Bananas", "Apples", "Oranges", "Bananas"],
"Amount": [4, 1, 2, 2, 4, 5],
"City": ["SF", "SF", "SF", "Montreal", "Montreal", "Montreal"]
})
fig = px.bar(df, x="Fruit", y="Amount", color="City", barmode="group")
fig.update_layout(
plot_bgcolor=colors['background'],
paper_bgcolor=colors['background'],
font_color=colors['text']
)
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 framework for your data.', style={
'textAlign': 'center',
'color': colors['text']
}),
dcc.Graph(
id='example-graph-2',
figure=fig
)
])
if __name__ == '__main__':
app.run_server(debug=True)
浏览器效果:
说明:
dash_html_components 库除了为HTML参数提供了关键字外,还为每个HTML标签提供了组件类;
示例中,使用 style 属性修改了 html.Div 和 html.H1components 行内样式;
dash_html_components 的 HTML 属性,与 HTML 属性之间存以下几点差异:
HTML中的style属性是以分号分隔的字符串;Dash用的是字典;
Dash的style字典键是 camelCased(驼峰式) 命名法,HTML 中的 text-align,在style字典中为 textAlign;
HTML 的 class 属性,对应Dash中的 className;
HTML 的子项是通过 children关键字参数指定的,按照惯例,这始终是第一个参数,经常被省略;
除了上述外,其他所有HTML属性与标签,在Python中都有效。
3.3 实例3:表格
import dash
from dash import html
import plotly.express as px
import pandas as pd
df = pd.read_csv('data/usa-agricultural-exports-2011.csv')
def generate_table(dataframe, max_rows=10):
return html.Table([
html.Thead(
html.Tr([html.Th(col) for col in dataframe.columns])
),
html.Tbody([
html.Tr([
html.Td(dataframe.iloc[i][col]) for col in dataframe.columns
]) for i in range(min(len(dataframe), max_rows))
])
])
app = dash.Dash(__name__)
app.layout = html.Div([
html.H4(children='US Agriculture Exports (2011)'),
generate_table(df)
])
if __name__ == '__main__':
app.run_server(debug=True)
浏览器效果:
说明
在Python中定义方法,Dash通过调用,可以创建复杂的可重用组件,如表格等,无需切换上下文或语言;
本示例实现的功能,是从Pandas的数据帧生成“表格”。
3.4 实例4:散点图
import dash
from dash import dcc
from dash import html
import plotly.express as px
import pandas as pd
app = dash.Dash(__name__)
df = pd.read_csv('data/gdp-life-exp-2007.csv')
fig = px.scatter(df, x="gdp per capita", y="life expectancy",
size="population", color="continent", hover_name="country",
log_x=True, size_max=60)
app.layout = html.Div([
dcc.Graph(
id='life-exp-vs-gdp',
figure=fig
)
])
if __name__ == '__main__':
app.run_server(debug=True)
浏览器效果:
说明
dash_core_components 库包含一个名为的组件Graph,其使用开源JavaScript图形库plotly.js ,呈现交互式数据可视化;
Plotly.js 支持超过35种图表类型,并以矢量质量SVG和高性能WebGL的方式呈现图表;
dash_core_components.Graph 组件的参数 figure ,与开放源码的 Python 图形库 Plotly 中的参数 figure使用方法,都是一样的;
这些图表具有互动性和响应性:
将鼠标悬停在点上以查看其值;
单击图例项以切换轨迹;
单击并拖动以缩放;
按住shift后单击并拖动,可以平移图表;
3.5 实例5:Markdown
import dash
from dash import dcc
from dash import html
import plotly.express as px
import pandas as pd
app = dash.Dash(__name__)
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通过 dash_html_components 库可以实现文本编写,但在HTML中编写文本,比较繁琐,需要写入大量的格式化文本,推荐使用库中的Markdown组件;
Dash使用 Markdown 的CommonMark规范;
3.6 实例6:网页元素
import dash
from dash import dcc
from dash import html
import plotly.express as px
import pandas as pd
app = dash.Dash(__name__)
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: '标签 {}'.format(i) if i == 1 else str(i) for i in range(1, 6)})
], style={'columnCount': 2})
if __name__ == '__main__':
app.run_server(debug=True)
浏览器效果:
说明
本示例中,展示了下拉列表单选、下拉列表多选、单选按钮、多选按钮、文本输入框、滑动条;
dash_core_components 包含一系列高级别的组件,如下拉列表、图形、Markdown文本等;
与所有Dash组件一样,这些组件都是声明式的,组件的关键字参数也一样,每个选项都可以进行配置;
在Dash核心组件库中,可以查看所有可用的组件。
|