如何在Python Dash中用CSS实现4个小图表的对齐铺满布局?
解决Python Dash中4个小图表的布局对齐问题
问题说明
本人CSS基础有限,需要解决Python Dash的图表布局问题:将4个小图表对齐在大图表下方,铺满该区域的整个页面宽度,当前布局接近对齐但未达预期效果。
修改后的完整代码
import plotly.express as px from dash import Dash, html, dcc import dash_bootstrap_components as dbc # 假设map_pick、map_ban、map_side、opcoes已提前定义 fig_pick = px.pie(map_pick, values='Total', names='Map', title='Mapas com mais Picks no Valorant Champions 2022') # 移除固定width,让图表自适应容器 fig_pick.update_layout(margin=dict(l=40, r=25, t=45, b=20), height=300, template='darkly') fig_ban = px.pie(map_ban, values='Total', names='Map', title='Mapas com mais Bans no Valorant Champions 2022') fig_ban.update_layout(margin=dict(l=40, r=55, t=45, b=20), height=300, template='darkly') fig_atk = px.bar(map_side, x='Map', y='Atk Wins', color='Map', title='Taxa de Vitórias nos mapas no lado de ataque pelo Valorant Champions em %:', labels={ 'Atk Wins': 'Vitórias no lado de Ataque em %', 'Map': 'Mapa' }, text='Atk Wins') fig_atk.update_traces(textposition='inside',texttemplate='%{text:.3s}') fig_atk.update_layout(margin=dict(l=40, r=55, t=45, b=20), height=300, template='darkly') fig_def = px.bar(map_side, x='Map', y='Def Wins', color='Map', title='Taxa de Vitórias nos mapas no lado de defesa pelo Valorant Champions em %:', labels={ 'Def Wins': 'Vitórias no lado de Defesa em %', 'Map': 'Mapa' }, text='Def Wins') fig_def.update_traces(textposition='inside',texttemplate='%{text:.3s}') fig_def.update_layout(margin=dict(l=40, r=55, t=45, b=20), height=300, template='darkly') app.layout = html.Div(children=[ dbc.Row([ dbc.Col([ dbc.Card([ html.H5('Opcões'), dcc.Dropdown(opcoes, value = 'ACS' , id='check_opcao', style={'width': '100%'}), ],style={'height': '94vh', 'margin': '20px', 'padding': '20px', 'width': '300px'}) ], sm=2), dbc.Col([ # 大图表去掉固定宽度,自适应父容器 dbc.Row([dcc.Graph( id='grafico_gc_players', style={ 'width': '100%'})], style={ 'margin': '20px'}), dbc.Row([ # 每个Col占满对应空间,添加内边距让图表间距均匀 dbc.Col([dcc.Graph(id='map_pick', figure=fig_pick)], sm=3, style={'padding': '5px'}), dbc.Col([dcc.Graph(id='map_ban', figure=fig_ban)], sm=3, style={'padding': '5px'}), dbc.Col([dcc.Graph(id='map_side_atk', figure=fig_atk )], sm=3, style={'padding': '5px'}), dbc.Col([dcc.Graph(id='map_side_def', figure=fig_def )], sm=3, style={'padding': '5px'}) ], style={'margin': '0 20px'}) ],sm=10) ]) ])
关键调整点
- 移除图表固定宽度:所有
fig.update_layout()中的width参数都删掉,让图表自动适配所在Col的宽度,避免固定宽度导致的溢出或留白。 - 大图表自适应宽度:把大图表的
style={'width': '1100px'}改成width='100%',确保它和下方小图表所在的Col宽度一致。 - 调整Col的内边距:给每个小图表的Col添加
style={'padding': '5px'},让图表之间的间距均匀,同时铺满整个Row宽度。 - 清理多余margin:去掉大图表Row中的
margin-right:70px,避免挤压下方小图表的可用空间。
内容的提问来源于stack exchange,提问作者Luis Sanches
相关产品推荐
相关产品推荐

