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

如何移除Plotly中Choropleth子图的上下边距

解决Plotly并排Choropleth子图未铺满高度的问题

问题核心是Plotly的地理子图默认会维持地理投影的固有宽高比,不会自动填充子图的垂直空间。要让每个子图铺满整体高度,需要手动指定每个geo组件的domain范围,强制其占满子图的垂直区域。

修改后的完整代码

import json
from plotly.subplots import make_subplots
import plotly.graph_objects as go

# 定义水平间距和子图数量
horizontal_spacing = 0.0025
total_cols = 3

# 计算每个子图的x轴domain范围,适配水平间距
x_domain_ranges = [
    [0, (1 - (total_cols - 1) * horizontal_spacing) / total_cols],
    [(1 - (total_cols - 1) * horizontal_spacing) / total_cols + horizontal_spacing, 
     2 * (1 - (total_cols - 1) * horizontal_spacing) / total_cols + horizontal_spacing],
    [2 * (1 - (total_cols - 1) * horizontal_spacing) / total_cols + 2 * horizontal_spacing, 1]
]

fig = make_subplots(rows=1, cols=3,
                    specs=[[{"type": "choropleth"}, {"type": "choropleth"}, {"type": "choropleth"}]],
                    horizontal_spacing=horizontal_spacing)

fig.update_layout(height=400, width=800,
                  margin=dict(t=0, r=0, b=0, l=0),
                  coloraxis_showscale=False)

for i, column in enumerate(["m_rugged", "cm3_over_1999", "bip"]):
    fig.add_trace(
        go.Choropleth(
            locations=minidf.index,
            z=minidf[column].astype(float),
            geojson=json.loads(minidf[["geometry"]].to_json()),
            showscale=False
        ),
        col=i+1, row=1)
    
    # 为每个子图设置geo的domain:y轴占满整个高度,x轴用计算好的范围
    fig.update_geos(
        fitbounds="locations",
        visible=True,
        domain=dict(x=x_domain_ranges[i], y=[0, 1]),
        row=1, col=i+1
    )

fig.show()

关键修改点

  • 计算x轴domain范围:根据子图数量和水平间距,分配每个子图的水平占比,避免重叠或留白。
  • 设置geo的domain参数:通过domain=dict(y=[0,1])强制地理区域填充子图的整个垂直空间,同时指定x轴范围保证子图紧密排列。
  • 针对每个子图单独更新geo:使用row和col参数确保每个子图的geo配置独立生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 15:25:09