【Dash】Dash Layout

一、Dash Layout

Dash apps are composed of two parts. The first part is the 'layout', which describes what the app looks like. The second part describes the interactivity of the app.

To get started, create a file namedapp.py , copy the code below into it, and then run it with python app.py

python 复制代码
from dash import Dash, html, dcc
import plotly.express as px
import pandas as pd

app = Dash()

df = pd.DataFrame({
    'Fruit': ['Apples', 'Oranges', 'Bananas', 'Apples', 'Oranges', 'Bananas'],
    'Amout': [4, 1, 2, 2, 4, 5],
    'City': ['SF', 'SF', 'SF', 'Montreal', 'Montreal', 'Montreal']
})


fig = px.bar(df, x='Fruit', y='Amout', 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(debug=True)

二、解读

python 复制代码
from dash import Dash, html, dcc
import plotly.express as px
import pandas as pd
  • 导入 Dash 库中的Dash 类(用于 Dash应用)、html模块(提供HTML元素)和 dcc 模块(提供Dash核心组件)
  • 导入 plotly.express 库,简称 px,用于创建图表
  • 导入 pandas 库,简称pd,用于数据处理
python 复制代码
df = pd.DataFrame({
    'Fruit': ['Apples', 'Oranges', 'Bananas', 'Apples', 'Oranges', 'Bananas'],
    'Amount': [4, 1, 2, 2, 4, 5],
    'City': ['SF', 'SF', 'SF', 'Montreal', 'Montreal', 'Montreal']
})
  • 创建一个包含水果名称、数量、城市的数据
python 复制代码
fig = px.bar(df, x='Fruit', y='Amount', color='City', barmode='group')
  • 使用 plotly.express 的 bar 函数创建一个分组条形图,其中 x 轴是水果、y轴是数量、颜色表示不同的城市,'barmode'参数设置为'group',表示将相同水果的条形分组显示。
python 复制代码
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
            )
])
  • 设置Dash应用的布局,使用html.Div作为容器。
  • 'children'参数用于定义Div容器中的子元素。
  • 创建一个H1标题元素,显示文本'Hello Dash'。
  • 创建一个Div元素,并在其中放置文本,这段文本是对Dash的简单介绍。
  • 创建一个dcc.Graph组件,用于在Dash应用中嵌入图表。
  • 为图表组件设置一个唯一的ID,这个ID用于在回调函数中引用这个图表。
  • 将之前创建的条形图fig赋值给图表组件的figure属性,这样图表就会在应用中显示。
相关推荐
深蓝海拓4 小时前
基于QtPy (PySide6) 的PLC-HMI工程实战记录(七)创建适合HMI项目的数字输入/显示类部件
python
INGNIGHT4 小时前
1908 · 布尔表达式求值(stack单调栈&dfs)
开发语言·c++·算法
MartinYeung54 小时前
[论文学习]MPIB:医疗提示注入基准——针对LLM临床安全性的系统性评估
人工智能·python·学习
এ慕ོ冬℘゜4 小时前
深入理解浏览器全屏 API:从 requestFullscreen 到全屏实战
开发语言·html
用户8356290780514 小时前
使用 Python 为 PowerPoint 演示文稿添加评论
后端·python
阿图灵5 小时前
OpenCV 绘图五件套:画圆、文本、线段、矩形与椭圆
图像处理·人工智能·python·opencv·计算机视觉·绘图
web行路人5 小时前
AI全栈之旅 · 第一周总结
python
slacker-kian5 小时前
HuggingFace API加载模型超时:用 ModelScopeAPI 替代
人工智能·python·transformer·huggingface·blip·modelscope·blipprocessor
七夜zippoe5 小时前
DolphinDB 高可用部署实战:从容灾设计到故障自动转移
开发语言·python·高可用·容灾·dolphindb