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

Python Dash如何将仪表板分为两列且保留图表全宽布局

实现方案

首先需要确保你已经安装dash-bootstrap-components依赖,且初始化app时引入bootstrap样式,dbc的栅格布局才能正常生效:

import dash
from dash import html, dcc
import dash_bootstrap_components as dbc
import dash_daq as daq

# 初始化app必须引入bootstrap样式
app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
# 此处保留你原有定义的all_options、options1变量即可

修改后的布局代码如下,完全符合你要的两列分布、底部图表占满全宽的需求:

app.layout = dbc.Container([
    # 第一行:两列分别放置Material1、Material2组件
    dbc.Row([
        # 第一列:Material1区域,占一半宽度,内容水平居中
        dbc.Col([
            html.Label('Material 1'),
            dcc.Dropdown(
                id='dropdown1',
                options=[{'label': k, 'value': k} for k in all_options.keys()],
                value=options1[0],
                style={'width': '400px'}
            ),
            html.Br(),
            html.Label('m3'),
            daq.NumericInput(
                id='numeric-input-1',
                min=0,
                max=200,
                value=0,
                style={'width': '200px'}
            )
        ], width=6, className='d-flex flex-column align-items-center'),

        # 第二列:Material2区域,占另一半宽度,内容水平居中
        dbc.Col([
            html.Label('Material 2'),
            dcc.Dropdown(
                id='dropdown2',
                options=[{'label': k, 'value': k} for k in all_options.keys()],
                value=options1[0],
                style={'width': '400px'}
            ),
            html.Br(),
            html.Label('m3'),
            daq.NumericInput(
                id='numeric-input-2',
                min=0,
                max=200,
                value=0,
                style={'width': '200px'}
            )
        ], width=6, className='d-flex flex-column align-items-center'),
    ], className='mb-4'),

    # 第二行:Indicator下拉,占满全宽
    dbc.Row([
        dbc.Col([
            html.Label('Indicator'),
            dcc.Dropdown(
                id='dropdown3',
                style={'width': '400px'}
            )
        ], width=12)
    ], className='mb-4'),

    # 第三行:底部图表,占满全宽
    dbc.Row([
        dbc.Col([
            dcc.Graph(
                id='display-selected-values',
                style={'width': '100%', 'height': '500px'}
            )
        ], width=12)
    ])
], fluid=True)

关键配置说明

  • width=6对应bootstrap 12列栅格系统,两列各占一半页面宽度
  • className='d-flex flex-column align-items-center'是bootstrap内置工具类,实现列内元素垂直排列、水平居中的效果
  • fluid=True让整个容器自适应浏览器宽度,如果你需要固定宽度可以删除该参数
  • 如果你不想引入bootstrap样式,也可以用原生CSS实现:给两个并列的列设置style={'width': '50%', 'display': 'inline-block', 'vertical-align': 'top', 'text-align': 'center'}即可实现同等效果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 23:18:03