【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属性,这样图表就会在应用中显示。
相关推荐
才不做选择8 分钟前
基于 YOLOv8 的部落冲突 (Clash of Clans) 目标检测系统
人工智能·python·yolo·目标检测
广州服务器托管10 分钟前
[2026.1.6]WINPE运维版20260106,带网络功能的PE维护系统
运维·开发语言·windows·计算机网络·个人开发·可信计算技术
龘龍龙16 分钟前
Python基础学习(十一)
python·学习·mysql
a努力。18 分钟前
京东Java面试被问:双亲委派模型被破坏的场景和原理
java·开发语言·后端·python·面试·linq
冰暮流星19 分钟前
javascript赋值运算符
开发语言·javascript·ecmascript
谢娘蓝桥19 分钟前
adi sharc c/C++ 语言指令优化
开发语言·c++
程序员小远20 分钟前
UI自动化测试框架:PO模式+数据驱动
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例
2501_9418053124 分钟前
从微服务网关到统一安全治理的互联网工程语法实践与多语言探索
前端·python·算法
刘975326 分钟前
【第25天】25c#今日小结
java·开发语言·c#
Chris_121928 分钟前
Halcon学习笔记-Day5
人工智能·笔记·python·学习·机器学习·halcon