Dash入门

1. 说明

 大数据开发过程中,我们常常需要向别人展示一些统计结果,有时候还是实时的统计结果。最好能以网页方式提供,让别人在他的机器上,使用浏览器也能访问。这时候统计工具往往使用Python,而把分析图表画出来使用JavaScript,需要搭建web服务,还涉及中间过程的数据衔接。而Dash能帮我们实现以上所有的工作。

 Dash是Python的一个库,使用pip即可安装。用它可以启动一个http server, python调用它做图,而它内部将这些图置换成JavaScript显示,进行数据分析和展示。

2. 安装

$ pip install dash
$ pip install dash-renderer
$ pip install dash-html-components
$ pip install dash-core-components

 其中html与网页相关,比如用它实现Title显示及一些与用户的交互操作,core是绘图部分,像我们常用的柱图,饼图,箱图,线图,都可以用它实现。

3. 简单demo

(1) 代码

# -*- coding: utf-8 -*-

import dash
import dash_core_components
import dash_html_components
import numpy

x = numpy.linspace(0, 2 * numpy.pi, 100)
y = 10 * 2 * numpy.cos(t)

app = dash.Dash()
app.layout = dash_html_components.Div(children=[
 dash_html_components.H1(children='Testme'),
 dash_core_components.Graph(
 id='curve',
 figure={
 'data': [
 {'x': x, 'y': y, 'type': 'Scatter', 'name': 'Testme'},
 ],
 'layout': {
 'title': 'Test Curve'
 } } )
])

if __name__ == '__main__':
 app.run_server(debug=True, host='0.0.0.0', port=8051)

(2) 运行结果

图片.png

(3) 注意事项
 需要注意的是最后一句中的宿主机host='0.0.0.0',默认是127.0.0.1,这样在其它机器访问本机启动的dash以及在docker启动dash时可能遇到问题,设置成0.0.0.0后,通过本机上的任意一个IPV4地址都能访问到它。

4. 与Flask相结合支持显示多个页面

 用上述方法,可以提供单个网页显示,但如果需要展示的内容很多,或者需要分类展示时,就需要提供多个界面以及在各个界面间跳转。Flask是一个使用 Python 编写的轻量级 Web 应用框架,Dash的Web框架就是调用它实现的,在程序中结合二者,即可以显示一网页,还能实现Dash画图功能,还能相互调用,具体见下例。

# -*- coding: utf-8 -*-

import numpy as np
import pandas as pd

from flask import Flask
import dash
import dash_core_components as dcc
import dash_html_components as html

server = Flask(__name__)
app1 = dash.Dash(__name__, server=server, url_base_pathname='/dash/')
app1.layout = html.Div([
    html.Div(
        children=[html.H1(children='趋势 1'),]
    )    
    ])

@server.route('/test')
def do_test():
    return "aaaaaaaaaaaaaaaaa"

@server.route('/')
def do_main():
    return "main"

if __name__ == '__main__':
    server.run(debug=True, port=8501, host="0.0.0.0")

 此时,在浏览器中分别打开:http://0.0.0.0:8501/, http://0.0.0.0:8501/testhttp://0.0.0.0:8501/dash,这时可以分别看dash生在网页和普通网页。

5. 各种常用图

(1) 环境
 三个例中使用的数据库中sklearn自带的iris数据集的前30个实例,以test*方式调用每种绘图函数

import dash
import dash_core_components
import dash_html_components
import numpy as np
from sklearn import datasets
import pandas as pd
import plotly.figure_factory as ff

iris=datasets.load_iris()
data = pd.DataFrame(iris.data, columns=['SpealLength', 'Spealwidth',
                                        'PetalLength', 'PetalLength'])
data = data[:30]

app = dash.Dash()
test4(app, data)
app.run_server(debug=True)

(2) 线图

def test1(app, data):
    y = np.array(data['SpealLength'])
    x = range(len(y))
    app.layout = dash_html_components.Div(children=[
        dash_html_components.H1(children='Demo'),
        dash_core_components.Graph(
            id='line',
            figure={
                'data': [
                    {'x': x, 'y': y, 'type': 'Scatter', 'name': 'Line'},
                ],
                'layout': {
                    'title': '线图'
                }
            }
        )
    ])

(3) 柱图

def test2(app, data):
    y = np.array(data['SpealLength'])
    x = range(len(y))
    app.layout = dash_html_components.Div(children=[
        dash_html_components.H1(children='Demo'),
        dash_core_components.Graph(
            id='bar',
            figure={
                'data': [
                    {'x': x, 'y': y, 'type': 'bar', 'name': 'Bar'},
                ],
                'layout': {
                    'title': '柱图'
                }
            }
        )
    ])

(4) 直方图

def test3(app, data):
    y = np.array(data['SpealLength'])
    app.layout = dash_html_components.Div(children=[
        dash_html_components.H1(children='Demo'),
        dash_core_components.Graph(
            id='hist',
            figure={
                'data': [
                    dict(
                        type='histogram', x=y, name='Hist'
                    )
                ],
                'layout': {
                    'title': '直方图'
                }
            }
        )
    ])

(5) 箱图

def test4(app, data):
    data['group1'] = data['SpealLength'].apply(lambda x: int(x * 4) / 4.0)
    x = data['group1'] # 按length分类,统计width
    y = np.array(data['Spealwidth'])
    app.layout = dash_html_components.Div(children=[
        dash_html_components.H1(children='Demo'),
        dash_core_components.Graph(
            id='box',
            figure={
                'data': [
                    dict(
                        type='box', x=x, y=y, name='Box'
                    )
                ],
                'layout': {
                    'title': '箱图'
                }
            }
        )
    ])

箱图比较特殊,它是按x的unique统计y的分布。

(6) 饼图

def test5(app, data):    
    data['group1'] = data['SpealLength'].apply(lambda x: int(x))
    tmp = data.groupby('group1').size().to_frame()
    tmp = tmp.rename(columns={0: 'num'})
    tmp = np.round(tmp, 4).reset_index(drop=False)

    app.layout = dash_html_components.Div(children=[
        dash_html_components.H1(children='Demo'),
        dash_core_components.Graph(
            id='pie',
            figure={
              'data': [
                    dict(
                        type='pie', name='Pie',
                        labels=tmp['group1'].tolist(),
                        values=tmp['num'].tolist(),
                    )                  
                ],
                'layout': {
                    'title': '饼图'
                }
            }
        )
    ])

(7) 图表

def test6(app, data):
    table = ff.create_table(data.head()) 
    for i in range(len(table.layout.annotations)):
        table.layout.annotations[i].font.size = 15
    app.layout = dash_html_components.Div(children=[
        dash_html_components.H1(children='Demo'),
        dash_core_components.Graph(
            id='table',
            figure=table
        )
    ])

6. 参考

(1) 官方demo
https://dash.plot.ly/gallery

(2) 支持多个网页的另一种方法
https://stackoverflow.com/questions/51946300/setting-up-a-python-dash-dashboard-inside-a-flask-app

(3) 最常用例程
https://dash.plot.ly/getting-started

(4) dash各种界面交互(最后边)
https://dash.plot.ly/getting-started

(5) dash交互中各种callback处理
https://dash.plot.ly/getting-started-part-2

 

  • 9
    点赞
  • 82
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值