Django 集成 Plotly-Dash:图表无法横向并排渲染问题求助
解决Django Dash中图表无法横向并排的问题
我看了你的代码,问题核心在于flex布局的应用对象搞错了——你给每个dcc.Graph单独设置了display: flex,但flex布局是需要给包含这些图表的父容器设置的,这样容器内的子元素才会自动横向排列。另外还有个小细节:代码里重复使用了id='graph2',这会导致Dash无法正确识别组件,必须保证每个组件的id唯一。
具体修改步骤
- 把需要横向并排的图表放到一个单独的父
Div中,给这个父容器设置display: flex属性,同时可以用gap控制图表间距。 - 移除每个图表自身的
display: flex样式,只保留宽度、边距这类控制自身尺寸的属性。 - 修正重复的组件id,避免Dash识别冲突。
修改后的核心布局代码
app.layout = html.Div(children=[ # 所有顶部元素 html.Div(children=[ html.Div(children=[ html.H1('Hello Dash'), html.Div(''' Dash: A web application framework for Python.'''), # 关键:用flex容器包裹需要并排的两个图表 html.Div([ dcc.Graph(id='graph1', figure=fig, style={"width": 500, "margin": 10}), dcc.Graph(id='graph2', figure=fig, style={"width": 500, "margin": 10}), ], style={'display': 'flex', 'gap': '20px'}), html.H3('Hello Dash'), # 修正重复id,改为graph4 dcc.Graph(id='graph4', figure=fig, style={"width": 500, "margin": 10}), ]), html.Div(children=[ html.H1('Hello Dash', style={"width":500, "margin": 0}), html.Div('''Dash: A web application framework for Python.''', style={"width":500, "margin": 0}), dcc.Graph(id='graph3', figure=fig, style={"width":500, "margin": 0}), ]), html.H1('Hello Dash'), html.Div('''Dash: A web application framework for Python.'''), dcc.Graph(id='graph5', figure=fig, style={"width":500, "margin": 0} ), ], className='row'), # 表格部分保持不变 html.Div([ html.H1(children='Hello Dash'), html.Div(children=''' Dash: A web application framework for Python. '''), dash_table.DataTable( id='table', columns=[{"name": i, "id": i} for i in df_bar.columns], data=df_bar.to_dict('records'), sort_action='native', filter_action='native', export_format='csv', style_cell={'textAlign': 'center', 'font-size' : '16px','width': '10px', 'overflow': 'hidden' }, style_data_conditional=[ { 'if': {'row_index': 'odd'}, 'backgroundColor': 'rgb(248, 248, 248)' } ], style_header={ 'backgroundColor': 'rgb(230, 230, 230)', 'fontWeight': 'bold', 'font-size' : '20px' } ) ], className='six columns') ])
额外说明
gap: '20px'用来控制两个图表之间的间距,你可以根据需求调整数值。- 如果希望图表在屏幕空间不足时自动换行,可以给父容器加上
flex-wrap: wrap属性。 - 你当前使用的
dash_core_components和dash_html_components是旧版API,现在Dash官方推荐使用dash.dcc和dash.html,如果你的Django Dash版本支持,建议升级导入方式:from dash import dcc, html
这样修改后,两个图表应该就能正常横向并排显示了。如果还有布局异常,可以检查外部样式表是否存在覆盖flex属性的规则。
内容的提问来源于stack exchange,提问作者Murcielago
相关产品推荐
相关产品推荐

