Web可视化包Dash学习

打算复现Grad-CAM,但是感觉服务器上的话不用jupyter搞可视化有点麻烦,用jupyter的话不适合搞代码量大的程序,所以干脆找找有没有解决我这个需求的工具,于是就找到了dash这个框架。

Dash是一个用于构建Web应用程序的高效Python框架。

Dash写在Flask,Plotly.js和React.js之上,非常适合在纯Python中,使用高度自定义的用户界面,构建数据可视化应用程序。它特别适合使用Python进行数据分析的人。

但是要学这个就要学下他们家的可视化库Plotly,学习成本不大,于是就决定入坑。


Outline

  1. 搭建基本框架
  2. 可视化图的尝试
  3. 交互
  4. 自己定制的UI

基本框架

Flask有个优点是实时渲染,边改代码边看样式(双屏打开😁)

import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px
import pandas as pd

# css样式
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
# 实例化一个dash.Dash
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

# assume you have a "long-form" data frame
# see https://plotly.com/python/px-arguments/ for more options
# DataFrame数据
df = pd.DataFrame({
    "Fruit": ["Apples", "Oranges", "Bananas", "Apples", "Oranges", "Bananas"],
    "Amount": [4, 1, 2, 2, 4, 5],
    "City": ["SF", "SF", "SF", "Montreal", "Montreal", "Montreal"]
})

# plotly绘制条形图
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 Python.
    '''),

    dcc.Graph(
        id='example-graph',
        figure=fig
    )
])

if __name__ == '__main__':
    # 类似Flask开启server
    # server
    # host 0.0.0.0
    # port 8033  不跟其他人冲突就好-。-
    app.run_server(debug=True)

常用组件

  • Div

  • H1

  • Table

    
    # 定义表格组件
    def create_table(df, max_rows=12):
        """基于dataframe,设置表格格式"""
        
        table = html.Table(
            # Header
            [
                html.Tr(
                    [
                        html.Th(col) for col in df.columns
                    ]
                )
            ] +
            # Body
            [
                html.Tr(
                    [
                        html.Td(
                            df.iloc[i][col]
                        ) for col in df.columns
                    ]
                ) for i in range(min(len(df), max_rows))
            ]   
        )
        return table
    
  • Markdown

    dcc.Markdown

  • 交互组件

    https://dash.plotly.com/dash-core-components