使用Dash开发交互式数据可视化网页--页面布局

简介: Dash应用布局后续的操作前,需要安装如下Python包pip install dash==0.20.0 # The core dash backendpip install dash-renderer==0.

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_componentsdash_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_componentsMarkdown提供了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提供.

参考资料:

目录
相关文章
|
9月前
|
数据可视化 搜索推荐 API
一款功能强大的Unity数据可视化图表库
今天大姚分享一款免费(基于MIT License协议)、开源、功能强大、简单易用、可配置的Unity数据可视化图表库:XCharts。
192 1
|
3月前
|
编解码 数据可视化 前端开发
如何使用 D3.js 创建一个交互式的地图可视化?
如何使用 D3.js 创建一个交互式的地图可视化?
|
4月前
|
移动开发 数据可视化 小程序
DIY可视化UniApp可视化入门教程
DIY可视化UniApp可视化入门教程
94 0
|
6月前
|
JavaScript 数据可视化 BI
echarts的使用 超好用的报表制作、数据的图形化展示
您提供的链接是关于echarts使用的博客文章,它介绍了如何使用echarts进行数据的图形化展示,包括制作报表和图表。echarts是一个强大的数据可视化工具,能够创建折线图、柱状图、饼图等多种图表类型。文章还提供了一个Demo演示和项目结构的图片,以及官网链接供读者参考。
echarts的使用 超好用的报表制作、数据的图形化展示
|
6月前
|
数据可视化 前端开发 JavaScript
Echarts+JS实现数据分析可视化大屏!!附源码!!
Echarts+JS实现数据分析可视化大屏!!附源码!!
|
8月前
|
数据可视化 大数据 API
【推荐100个unity插件之22】基于UGUI的功能强大的简单易用的Unity数据可视化图表插件——XCharts3.0插件的使用
【推荐100个unity插件之22】基于UGUI的功能强大的简单易用的Unity数据可视化图表插件——XCharts3.0插件的使用
357 0
|
9月前
|
存储 JavaScript 前端开发
JavaScript复杂功能实现:实时数据可视化图表
JavaScript复杂功能实现:实时数据可视化图表
|
数据可视化 定位技术
漏刻有时数据可视化Echarts组件开发(22):echarts高端地图交互美化
漏刻有时数据可视化Echarts组件开发(22):echarts高端地图交互美化
279 0
漏刻有时数据可视化Echarts组件开发(22):echarts高端地图交互美化
|
前端开发 数据可视化 JavaScript
使用Dash快速构建你的数据可视化前端
使用Dash快速构建你的数据可视化前端
586 0
|
监控 数据可视化 前端开发
前端数据可视化和动态图表库
前端数据可视化和动态图表库
382 0

热门文章

最新文章