You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Dash Bootstrap Components调整列高度并实现含第三、第四组件的布局

调整Dash Bootstrap布局以添加独立交互的折线图与数据表

已基于Dash Bootstrap Components完成页面基础布局,现需在中间区域(橙色块)添加两个新组件:第三组件为折线图,第四组件为对比数据表,要求两个组件支持独立交互与控制,以下是调整方案及代码:

import dash_bootstrap_components as dbc
from dash import Dash, html, dcc, Input, Output, dash_table
import pandas as pd
import plotly.express as px

# 生成示例数据(实际项目可替换为真实数据加载逻辑)
df = pd.DataFrame({
    'ID': ['A', 'A', 'A', 'B', 'B', 'B'],
    'Date': pd.date_range(start='2024-01-01', periods=6),
    'Value': [10, 15, 12, 8, 11, 9],
    'Compare_Value': [12, 14, 13, 7, 10, 8]
})

app = Dash(external_stylesheets=[dbc.themes.BOOTSTRAP])

sidebar = dbc.Nav(
    [dbc.NavLink(f"Item {i+1}", href=f"/page-{i+1}") for i in range(90)],
    pills=True,
    vertical=True,
    className="mt-3"
)

app.layout = html.Div([
    html.Br(),
    dbc.Container(
        [
            dbc.Row(
                [
                    # 左侧导航列
                    dbc.Col(
                        [
                            html.H2(
                                "左侧导航",
                                className="text-center sticky-top",
                                style={"background-color": "yellow"}
                            ),
                            sidebar,
                        ],
                        className="h-100 overflow-scroll",
                        style={"background-color": "yellow"},
                        width=3,
                        xs=5, sm=4, md=3, lg=3, xl=3
                    ),
                    # 中间内容列:拆分上下区域放折线图和数据表
                    dbc.Col(
                        [
                            # 顶部:折线图区域
                            html.Div([
                                html.H3("折线图", className="text-center"),
                                # 交互控件:选择ID
                                dbc.Label("选择ID:"),
                                dcc.Dropdown(
                                    df['ID'].unique(),
                                    value=df['ID'].unique()[0],
                                    id='id-selector'
                                ),
                                # 折线图组件
                                dcc.Graph(id='line-chart', style={"height": "70%"})
                            ], style={"height": "50%", "background-color": "orange", "padding": "1rem"}),
                            # 底部:数据表区域
                            html.Div([
                                html.H3("对比数据表", className="text-center"),
                                # 可选:数据表专属交互控件(比如日期范围选择)
                                dbc.Label("选择日期范围:"),
                                dcc.DatePickerRange(
                                    id='date-range',
                                    min_date_allowed=df['Date'].min(),
                                    max_date_allowed=df['Date'].max(),
                                    start_date=df['Date'].min(),
                                    end_date=df['Date'].max()
                                ),
                                # 对比数据表组件
                                dash_table.DataTable(
                                    id='compare-table',
                                    columns=[{"name": col, "id": col} for col in df.columns],
                                    page_size=10,
                                    style_table={"overflowY": "auto", "height": "70%"}
                                )
                            ], style={"height": "50%", "background-color": "#ffcc80", "padding": "1rem"})
                        ],
                        width=5,
                        xs=1, sm=3, md=5, lg=5, xl=5
                    ),
                    # 右侧内容列
                    dbc.Col(
                        [
                            html.H1("右侧内容", className="text-center"),
                            # 可添加其他辅助组件
                        ],
                        style={"height": "100%", "background-color": "yellow"},
                        width=4,
                        xs=6, sm=5, md=4, lg=4, xl=4
                    ),
                ],
                className="vh-100",
                justify='start'
            ),
        ],
        style={
            "background-color": "green",
            "padding": "0 1rem",
            "margin-left": "0",
            "margin-right": "0"
        },
        fluid=True,
    )
])

# 折线图回调(独立交互)
@app.callback(
    Output('line-chart', 'figure'),
    Input('id-selector', 'value')
)
def update_line_chart(selected_id):
    filtered_df = df[df['ID'] == selected_id]
    fig = px.line(filtered_df, x='Date', y='Value', title=f"ID {selected_id} 趋势")
    return fig

# 数据表回调(独立交互)
@app.callback(
    Output('compare-table', 'data'),
    Input('date-range', 'start_date'),
    Input('date-range', 'end_date')
)
def update_table(start_date, end_date):
    filtered_df = df[(df['Date'] >= start_date) & (df['Date'] <= end_date)]
    return filtered_df.to_dict('records')

if __name__ == "__main__":
    app.run_server(debug=True)

调整要点说明

  • 布局重构:将中间橙色列拆分为上下两个等高区域,分别承载折线图和数据表,通过内边距优化组件显示空间。
  • 组件添加:
    • 折线图用dcc.Graph作为容器,搭配ID选择下拉框实现交互筛选;
    • 对比数据表用dash_table.DataTable,搭配日期范围选择器作为专属交互控件。
  • 独立交互实现:通过两个完全独立的回调函数分别控制折线图和数据表的更新逻辑,两者操作互不干扰,满足独立交互需求。
  • 数据适配:内置示例DataFrame,实际项目可替换为真实数据加载逻辑(如读取CSV、数据库查询等)。

内容的提问来源于stack exchange,提问作者dsapprentice

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 13:12:56