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

Plotly水平堆叠条形图数字显示方向异常问题求助

解决Plotly水平堆叠条形图文本显示角度不一致的问题

我完全懂你碰到的这个糟心问题——用textposition="auto"的时候,Plotly会根据文本所在条形的空间自动调整角度,结果一位数和两位数的显示方向乱掉了。要让所有数字都稳稳保持水平显示,只需要强制设置textangle=0就行,再搭配合适的textposition还能优化显示位置。

修改后的完整代码

fig = go.Figure()
fig.add_trace(go.Bar(
    x = publicstperc, 
    y = publicstate_df.index, 
    orientation = "h", 
    name = "Public", 
    marker_color = "rgb(41,84,140)", 
    text = publicstate_df["Number of Public Schools"], 
    textposition = "inside",  # 可选"inside"或"outside",按需调整
    textangle=0  # 核心设置:强制文本水平显示
))
fig.add_trace(go.Bar(
    x = privatenpperc, 
    y = privatenpstate_df.index, 
    orientation = "h", 
    name = "Private-Nonprofit", 
    marker_color = "rgb(86,149,232)", 
    text = privatenpstate_df["Number of Private-Nonprofit Schools"], 
    textposition = "inside",
    textangle=0
))
fig.add_trace(go.Bar(
    x = proprietaryperc, 
    y = proprietarystate_df.index, 
    orientation = "h", 
    name = "Proprietary", 
    marker_color = "rgb(179,232,255)", 
    text = proprietarystate_df["Number of Proprietary Schools"], 
    textposition = "inside",
    textangle=0
))
fig.update_xaxes(range=[0,100])
fig.update_layout(title_text = "School Types Participation by State", barmode='stack', height = 1250, width = 1000)
fig.show()

关键细节说明

  • textangle=0:这是解决问题的核心,直接强制所有文本保持0度水平状态,完全覆盖了textposition="auto"带来的自适应角度调整逻辑。
  • textposition:推荐用"inside"让文本嵌在条形内部,如果遇到条形太窄放不下的情况,换成"outside"也可以,只要搭配textangle=0就能保证水平显示。
  • 为啥textposition="auto"不行?因为当条形宽度较窄(比如对应一位数数值的条形),Plotly会自动旋转文本节省空间,结果就出现了角度不一致的情况,强制固定角度就能彻底避免这种问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:04:20