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

Plotly make_subplots设置vertical_spacing=0后底部大量空白如何解决?

解决Plotly水平条形图底部大量空白问题

问题出在你创建了3行1列的子图布局,但所有条形图都默认添加到了第一行子图,剩下的两行空着,直接导致了底部的大片空白。

修正方案:

  • 给每个add_trace指定对应的row参数,让每个分类的条形图分别放在第1、2、3行子图中
  • 隐藏所有子图的y轴刻度标签(避免重复冗余)
  • 保持紧凑的垂直间距,让整体布局更贴合需求

修改后的完整代码:

import plotly.graph_objects as go
import plotly.offline as opy
from plotly.subplots import make_subplots

def test():
    config = {'staticPlot': True}
    marker_color = 'rgba(81, 132, 4, 1)'

    fig = make_subplots(
        rows=3,
        cols=1,
        vertical_spacing=0,
        shared_xaxes=True,
    )

    fig.update_layout(
        margin = dict(t=10, b=10, r=0, l=0),
        plot_bgcolor = 'white',
        showlegend = False,
        autosize=True,
        xaxis=dict(showticklabels=False)
    )

    # 给每个trace指定对应的子图行
    fig.add_trace(go.Bar(
        y=['Category 1'],
        x=[202],
        text=[202],
        orientation='h',
        marker_color=marker_color,
        textposition='outside'
    ), row=1, col=1)
    
    fig.add_trace(go.Bar(
        y=['Category 2'],
        x=[310],
        text=[310],
        orientation='h',
        marker_color=marker_color,
        textposition='outside'
    ), row=2, col=1)
    
    fig.add_trace(go.Bar(
        y=['Category 3'],
        x=[310],
        text=[310],
        orientation='h',
        marker_color=marker_color,
        textposition='outside'
    ), row=3, col=1)

    # 隐藏所有子图的y轴刻度标签,消除冗余显示
    fig.update_yaxes(showticklabels=False)

    return opy.plot(fig, output_type='div', config=config)

修改后每个条形图会对应到各自的子图行,底部的空白区域会被完全消除,整体布局也会更紧凑贴合你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 03:32:40