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

如何去除Plotly绘制Indicator子图时的上下空白区域?

解决Plotly Indicator子图上下空白过大的问题

针对你用Plotly创建Indicator子图时上下空白过多、设置margin仍无效的问题,可通过以下几个关键调整解决:

  • 精准设置margin参数:直接指定上下左右边距为极小值,覆盖Plotly默认的较大边距
  • 移除冗余布局元素:关闭图例(Indicator组件无需图例),避免占用空白空间
  • 优化子图垂直间距:单行列布局下无需设置过大的vertical_spacing,改为极小值
  • 调整Indicator的domain范围:缩小y轴方向的domain占比,避免组件过度拉伸占满子图高度
  • 指定固定图表高度:根据Indicator数量设置合适的高度,强制压缩上下空白

修改后的完整代码

def show_indicator_rma(total, opened, closed, received, not_received):
    # 调整垂直间距为极小值,单行列无需大间距
    fig = make_subplots(
        rows=1, cols=5,
        specs=[[{"type": "indicator"}]*5],
        horizontal_spacing=0.1,
        vertical_spacing=0.02
    )

    fig.add_trace(go.Indicator(
        mode="number+delta",
        value=total,
        title={"text": "Total units<br>", "font": {"size": 12}},  # 缩小标题字体减少空间占用
        domain={'x': [0, 1], 'y': [0.2, 0.8]},  # 限制Indicator在子图中间区域展示
    ), row=1, col=1)

    fig.add_trace(go.Indicator(
        mode="gauge+number",
        value=opened,
        domain={'x': [0, 1], 'y': [0.2, 0.8]},
        title={'text': "Open", "font": {"size": 12}},
        gauge={'axis': {'range': [None, total], 'visible': False}}
    ), row=1, col=2)

    fig.add_trace(go.Indicator(
        mode="gauge+number",
        value=closed,
        domain={'x': [0, 1], 'y': [0.2, 0.8]},
        title={'text': "Closed", "font": {"size": 12}},
        gauge={'axis': {'range': [None, total], 'visible': False}}
    ), row=1, col=3)

    fig.add_trace(go.Indicator(
        mode="gauge+number",
        value=received,
        domain={'x': [0, 1], 'y': [0.2, 0.8]},
        title={'text': "Received", "font": {"size": 12}},
        gauge={'axis': {'range': [None, total], 'visible': False}}
    ), row=1, col=4)

    fig.add_trace(go.Indicator(
        mode="gauge+number",
        value=not_received,
        domain={'x': [0, 1], 'y': [0.2, 0.8]},
        title={'text': "Not Received", "font": {"size": 12}},
        gauge={'axis': {'range': [None, total], 'visible': False}}
    ), row=1, col=5)

    # 核心布局优化
    fig.update_layout(
        margin=dict(l=10, r=10, t=20, b=20),  # 极小化边距
        height=200,  # 根据实际需求微调高度
        showlegend=False  # 关闭无用图例
    )
    return fig

关键调整说明

  • vertical_spacing=0.02:单行列布局下,原0.25的垂直间距会制造大量上下空白,改为极小值可快速压缩空间
  • domain={'x': [0,1], 'y': [0.2,0.8]}:让Indicator组件仅在子图的中间区域展示,避免占满整个子图高度导致上下留白
  • margin=dict(l=10, r=10, t=20, b=20):直接覆盖Plotly默认的较大边距,精准控制四周空白
  • height=200:指定固定高度,强制图表压缩冗余空白,可根据显示效果调整数值

内容的提问来源于stack exchange,提问作者Hảo Nguyễn Thị Phương

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 00:32:49