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

Plotly Express(Python3)中如何固定水平条形图的条形宽度?

解决Plotly Express水平条形图标签重叠及固定条形宽度问题

固定条形宽度的方法(无需Plotly GO)

在Plotly Express中,无需切换到Plotly GO就能直接固定条形宽度,这是解决小数据量下标签重叠的核心方案:

  • 设置固定条形宽度:
    在原有代码基础上添加update_traces(width=...),通过指定0-1之间的数值控制条形宽度(数值越小条形越窄):

    fig = px.bar(df, orientation='h')   
    
    fig.update_layout(
         yaxis_nticks = len(df.columns),
         height = len(df.columns)*30,
    ).update_xaxes(automargin = True,
    ).update_yaxes(automargin = True
    ).update_traces(width=0.4)  # 固定条形宽度
    
  • 动态适配条形宽度:
    若想根据数据量自动调整宽度,可结合数据长度计算合适的宽度值,避免固定值在极端场景下的不适配:

    # 数据量少时用较窄条形,数据量多时适当加宽
    bar_width = 0.3 if len(df.columns) < 5 else 0.6
    fig.update_traces(width=bar_width)
    

辅助优化标签显示的补充方案

除了固定条形宽度,还可配合以下设置进一步避免标签重叠:

  • 倾斜y轴标签:通过yaxis_tickangle调整标签角度,减少横向空间占用
  • 缩小标签字体:用yaxis_tickfont降低字体大小,释放更多空间
  • 强制显示全刻度:设置yaxis_tickmode='linear'确保每个类别都有独立刻度

示例代码:

fig.update_layout(
    yaxis_tickangle=30,  # 倾斜标签30度
    yaxis_tickfont=dict(size=10),  # 缩小标签字体
    yaxis_tickmode='linear'
)

内容的提问来源于stack exchange,提问作者Mr.Slow

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 01:41:27