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

如何使用Dash Plotly实现两个不同图表的并排布局?

如何用Dash Plotly实现两个图表并排显示

要让graph2和graph3并排展示,核心是利用Dash的网格布局系统分配宽度。你的现有代码思路方向是对的,以下是能确保布局生效的优化方案:

方案1:基于原生Dash HTML组件实现

如果继续使用原生Dash HTML组件,只需要调整几处细节即可:

import dash
import dash_html_components as html
import dash_core_components as dcc

# 假定graph1、graph2、graph3、multi_select_graph2、dropdown_graph3已提前定义

# 页面布局构建
header = html.H2(children="Fast Food in U.S.")

# 让row1占满整行(原代码的eight columns会留下空白列,可能干扰后续并排布局)
row1 = html.Div(children=[graph1], className="twelve columns")  

# 用row包裹两个子容器,每个子容器占6列,自动平分宽度实现并排
graphs_div = html.Div(children=[
    html.Div(children=[multi_select_graph2, graph2], className="six columns"),
    html.Div(children=[dropdown_graph3, graph3], className="six columns")
], className="row")  

# 外层容器设置居中、限制宽度,优化视觉效果
layout = html.Div(children=[header, row1, graphs_div], 
                  style={"max-width": "1200px", "margin": "0 auto", "padding": "20px"})

app = dash.Dash(__name__)
app.layout = layout

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

关键调整说明:

  • 将row1的类名从eight columns改为twelve columns,确保它占满整行,避免剩余空间导致后续布局错位;
  • graphs_div的row类是核心,内部两个six columns的子容器会自动平分一行宽度,实现并排;
  • 给外层容器添加max-width和margin: 0 auto,让整体布局居中且不会过宽。

方案2:使用dash-bootstrap-components(更推荐)

如果想要更稳定、响应式的布局,推荐用dash-bootstrap-components库,它基于Bootstrap框架,布局逻辑更清晰:

先安装依赖:

pip install dash-bootstrap-components

然后编写代码:

import dash
import dash_html_components as html
import dash_core_components as dcc
import dash_bootstrap_components as dbc

# 假定graph1、graph2、graph3、multi_select_graph2、dropdown_graph3已提前定义

# 页面布局构建
header = html.H2(children="Fast Food in U.S.", className="text-center mb-4")

# 第一行:graph1占满整行
row1 = dbc.Row(dbc.Col(graph1, width=12), className="mb-4")

# 第二行:两个图表各占6列,实现并排
graphs_row = dbc.Row([
    dbc.Col([multi_select_graph2, graph2], width=6),
    dbc.Col([dropdown_graph3, graph3], width=6)
])

# 外层容器用Bootstrap的Container,自带居中、间距样式
layout = dbc.Container([header, row1, graphs_row], fluid=False, className="py-4")

app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
app.layout = layout

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

这个方案的优势:

  • 无需手动写CSS类名,通过dbc.Row和dbc.Col直接配置宽度;
  • 内置Bootstrap的响应式布局,在手机、平板等设备上会自动适配;
  • 自带间距、对齐样式,页面排版更美观。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 03:56:08