Dash框架

Dash框架

在本章中,我们将详细讨论Dash框架。

Dash是一个开源的Python框架,用于构建分析性网络应用。它是一个强大的库,可以简化数据驱动的应用程序的开发。它对那些对网络开发不是很熟悉的Python数据科学家特别有用。用户可以使用dash在他们的浏览器中创建惊人的仪表盘。

构建在Plotly.js、React和Flask之上,Dash将现代UI元素如下拉、滑块和图表直接与你的分析性Python代码联系起来。

Dash应用程序包括一个Flask服务器,它通过HTTP请求使用JSON数据包与前端React组件进行通信。

Dash应用程序完全是用python编写的,所以不需要HTML或JavaScript

Dash设置

如果Dash还没有安装在你的终端上,那么请安装下面提到的Dash库。由于这些库正在积极开发中,所以要经常安装和升级。Python 2和3也被支持。

  • pip install dash==0.23.1 # 核心的dash后端
  • pip install dash-renderer==0.13.0 # dash前端
  • pip install dash-html-components==0.11.0 # HTML组件
  • pip install dash-core-components==0.26.0 # 强化组件
  • pip install plotly==3.1.0 # Plotly图形库

为了确保一切工作正常,在这里,我们创建了一个简单的dashApp.py文件。

Dash或应用程序的布局

Dash应用程序由两部分组成。第一部分是应用程序的 “布局”,基本上描述了应用程序的外观。第二部分描述了应用程序的交互性。

核心组件

我们可以用 dash_html_componentsdash_core_components 库来构建布局。Dash为应用程序的所有视觉组件提供了python类。我们也可以用JavaScript和React.js来定制我们自己的组件。

import dash_core_components as dcc

import dash_html_components as html

dash_html_components用于所有HTML标签,而dash_core_components用于用React.js构建的交互性。

使用上述两个库,让我们写一段代码,如下所示

app = dash.Dash()
app.layout = html.Div(children=[
   html.H1(children='Hello Dash'),
   html.Div(children='''Dash Framework: A web application framework for Python.''')
Python

而相应的HTML代码看起来是这样的 –

<div>
   <h1> Hello Dash </h1>
   <div> Dash Framework: A web application framework for Python. </div>
</div>
Python

编写简单的Dash应用程序

我们将学习如何使用上述库在文件 dashApp.py 中编写一个关于dash的简单例子

# -*- coding: utf-8 -*-
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 Framework: A web application framework for Python.'''),

   dcc.Graph(
      id='example-graph',
      figure={
         'data': [
            {'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': 'Delhi'},
            {'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name': u'Mumbai'},
         ],
         'layout': {
            'title': 'Dash Data Visualization'
         }
      }
   )
])

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

运行Dash应用程序

在运行Dash应用程序时注意以下几点。

(MyDjangoEnv) C:\Users\rajesh\Desktop\MyDjango\dash>python dashApp1.py

  • 为Flask应用程序 “dashApp1 “提供服务(懒惰加载)。

  • 环境:生产

警告:不要在生产环境中使用开发服务器。

请使用生产型WSGI服务器。

  • 调试模式:开

  • 用stat重新启动

  • 调试器已激活!

  • 调试器密码:130-303-947

  • 在http://127.0.0.1:8050/( CTRL+C退出)上运行。

127.0.0.1 - - [12/Aug/2018 09:32:39] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [12/Aug/2018 09:32:42] "GET /_dash-layout HTTP/1.1" 200 -
127.0.0.1 - - [12/Aug/2018 09:32:42] "GET /_dash-dependencies HTTP/1.1" 200 -
127.0.0.1 - - [12/Aug/2018 09:32:42] "GET /favicon.ico HTTP/1.1" 200 -
127.0.0.1 - - [12/Aug/2018 09:39:52] "GET /favicon.ico HTTP/1.1" 200 -
Python

在你的网络浏览器中访问 http:127.0.0.1:8050/ 。你应该看到一个看起来像这样的应用程序。

Dash框架

在上述程序中,需要注意的几个要点如下-

  • 应用程序的布局是由html.Div和dcc.Graph等 “组件 “树组成的。

  • dash_html_components库为每个HTML标签都有一个组件。html.H1(children = ‘Hello Dash’)组件在你的应用程序中生成一个

Hello Dash

HTML元素。

  • 不是所有的组件都是纯HTML。dash_core_components描述了更高层次的组件,这些组件是交互式的,通过React.js库用JavaScript、HTML和CSS生成。

  • 每个组件完全通过关键字属性来描述。Dash是声明式的:你将主要通过这些属性来描述你的应用程序。

  • children属性很特别。根据惯例,它总是第一个属性,这意味着你可以省略它。

  • Html.H1(children=’Hello Dash’)与html.H1(’Hello Dash’)是一样的。

  • 你的应用程序中的字体看起来会与这里显示的有一点不同。这个应用程序使用一个自定义的CSS样式表来修改元素的默认样式。自定义字体样式是允许的,但就目前而言,我们可以添加下面的URL或你选择的任何URL—

app.css.append_css ({“external_url”: https://codepen.io/chriddyp/pen/bwLwgP.css })来获取你的文件,以获得与这些例子相同的外观和感觉。

更多关于HTML的内容

dash_html_components库包含了每个HTML标签的一个组件类,以及所有HTML参数的关键字参数。

让我们在之前的应用程序文本中添加组件的内联样式–

# -*- coding: utf-8 -*-
import dash
import dash_core_components as dcc
import dash_html_components as html

app = dash.Dash()
colors = {
   'background': '#87D653',
   'text': '#ff0033'
}

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 Python.', style={
      'textAlign': 'center',
      'color': colors['text']
   }),

   dcc.Graph(
      id='example-graph-2',

      figure={
         'data': [
            {'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': 'Delhi'},
            {'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name': u'Mumbai'},
         ],
         'layout': {
            'plot_bgcolor': colors['background'],
            'paper_bgcolor': colors['background'],
            'font': {
               'color': colors['text']
            }
         }
      }
   )
])

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

在上面的例子中,我们用style属性修改了html.Div和html.H1组件的内联样式。

Dash框架

它在Dash应用程序中的渲染如下 −

Dash框架

dash_html_components和HTML属性之间有几个关键的区别 –

  • 对于Dash中的样式属性,你可以只提供一个字典,而在HTML中,它是分号分隔的字符串。

  • 样式字典的键是 CamelCased ,所以text-align变成了 textalign。

  • Dash中的ClassName类似于HTML的class属性。

  • 第一个参数是HTML标签的子代,它是通过children关键字参数指定的。

可重复使用的组件

通过用Python写标记,我们可以创建复杂的可重复使用的组件,如表格,而不需要切换上下文或语言-

下面是一个快速的例子,它从pandas数据框架中生成了一个 “表”。

import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd

df = pd.read_csv(
   'https://gist.githubusercontent.com/chriddyp/'
   'c78bf172206ce24f77d6363a2d754b59/raw/'
   'c353e8ef842413cae56ae3920b8fd78468aa4cb2/'
   'usa-agricultural-exports-2011.csv')

def generate_table(dataframe, max_rows=10):
   return html.Table(
      # Header
      [html.Tr([html.Th(col) for col in dataframe.columns])] +
      # Body
      [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()
app.layout = html.Div(children=[
   html.H4(children='US Agriculture Exports (2011)'),
   generate_table(df)
])

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

我们的输出将是这样的:-

Dash框架

关于可视化的更多信息

dash_core_components库包括一个名为 Graph的 组件

Graph使用开源的plotly.js JavaScript图形库渲染互动的数据可视化。Plotly.js支持大约35种图表类型,并以矢量质量的SVG和高性能的WebGL渲染图表。

下面是一个从Pandas数据框架中创建散点图的例子-

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

app = dash.Dash()

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

app.layout = html.Div([
   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'
         )
      }
   )
])

if __name__ == '__main__':
   app.run_server()
Python

上述代码的输出如下:

Dash框架

这些图表是交互式的,而且是响应式的。你可以将鼠标悬停在各点上以查看其数值,点击图例项目以切换痕迹,点击并拖动以缩放,按住shift,点击并拖动以平移。

标记

虽然dash通过dash_html_components库暴露了HTML的味道,但是用HTML来写你的副本可能很乏味。为了编写文本块,你可以使用dash_core_components库中的Markdown组件。

核心组件

dash_core_components包括一组更高级别的组件,如下拉菜单、图表、markdown、区块和更多。

像所有其他Dash组件一样,它们完全是声明式的描述。每一个可配置的选项都可以作为组件的一个关键字参数。

下面是一个例子,使用一些可用的组件-

# -*- coding: utf-8 -*-
import dash
import dash_core_components as dcc
import dash_html_components as html

app = dash.Dash()

app.layout = html.Div([
   html.Label('Dropdown'),
   dcc.Dropdown(
      options=[
         {'label': 'New York City', 'value': 'NYC'},
         {'label': u'Montréal', 'value': 'MTL'},
         {'label': 'San Francisco', 'value': 'SF'}
      ],
      value='MTL'
   ),

   html.Label('Multi-Select Dropdown'),
   dcc.Dropdown(
      options=[
         {'label': 'New York City', 'value': 'NYC'},
         {'label': u'Montréal', 'value': 'MTL'},
         {'label': 'San Francisco', 'value': 'SF'}
      ],
      value=['MTL', 'SF'],
      multi=True
   ),

   html.Label('Radio Items'),
   dcc.RadioItems(
      options=[
         {'label': 'New York City', 'value': 'NYC'},
         {'label': u'Montréal', 'value': 'MTL'},
         {'label': 'San Francisco', 'value': 'SF'}
      ],
      value='MTL'
   ),

   html.Label('Checkboxes'),
   dcc.Checklist(
      options=[
         {'label': 'New York City', 'value': 'NYC'},
         {'label': u'Montréal', 'value': 'MTL'},
         {'label': 'San Francisco', 'value': 'SF'}
      ],
      values=['MTL', 'SF']
   ),

   html.Label('Text Input'),
   dcc.Input(value='MTL', type='text'),

   html.Label('Slider'),
   dcc.Slider(
      min=0,
      max=9,
      marks={i: 'Label {}'.format(i) if i == 1 else str(i) for i in range(1, 6)},
      value=5,
   ),
], style={'columnCount': 2})

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

上述程序的输出结果如下 –

Dash框架

呼叫帮助

Dash组件是声明性的。这些组件的每一个可配置的方面在安装时都被设置为一个关键字参数。你可以在你的Python控制台中调用任何一个组件的帮助来了解更多关于一个组件和它的可用参数。下面给出了其中的一些参数

>>> help(dcc.Dropdown)
Help on class Dropdown in module builtins:
class Dropdown(dash.development.base_component.Component)
| A Dropdown component.
| Dropdown is an interactive dropdown element for selecting one or more

| items.
| The values and labels of the dropdown items are specified in the `options`
| property and the selected item(s) are specified with the `value` property.
|
| Use a dropdown when you have many options (more than 5) or when you are
| constrained for space. Otherwise, you can use RadioItems or a Checklist,
| which have the benefit of showing the users all of the items at once.
|
| Keyword arguments:
| - id (string; optional)
| - options (list; optional): An array of options
| - value (string | list; optional): The value of the input. If `multi` is false (the default)
-- More --
Python

总而言之,Dash应用程序的布局描述了应用程序的外观。布局是一个分层的组件树。dash_html_components库为所有的HTML标签和关键字参数提供了类,并描述了HTML属性,如style、className和id。dash_core_components库生成更高层次的组件,如控件和图形。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册