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

如何用Plotly创建带自定义位置文本标注的水平堆叠条形图?

图表选型建议
  • 继续采用Plotly的go.Bar实现即可,目标图属于堆叠式横向进度条,当前用barmode='stack'的思路完全匹配需求,无需更换图表类型。
  • 优化重点放在样式对齐、标注逻辑、颜色匹配和元素精简上。
具体实现修改方案

针对现有代码,做以下调整来复刻目标图表:

关键修改点

  1. 颜色匹配:替换主条形和背景条形的颜色,贴合目标图的视觉风格
  2. 数值标注:将百分比数值直接嵌入主条形内,替代原有的箭头标注
  3. 条形粗细:加宽条形宽度,更接近目标图的视觉比例
  4. 标签位置:将类别标签移至左侧(用y轴或自定义标注实现),修正原标注位置错误
  5. 轴设置:隐藏x轴并固定范围0-100,确保进度条完整填充横向空间

修改后的完整代码

import plotly.graph_objects as go

x_data = [23.1, 42.21]
y_data = ['Emission', 'Green Energy']
fig = go.Figure()

# 主进度条(对应目标图的彩色前景条)
fig.add_trace(go.Bar(
    y=y_data,
    x=x_data,
    orientation='h',
    marker=dict(
        color='#4ECDC4',  # 可根据目标图实际颜色微调
        line=dict(width=0)
    ),
    width=0.4,
    text=[f'{val}%' for val in x_data],
    textposition='inside',
    textfont=dict(color='white', size=12)
))

# 背景填充条
fig.add_trace(go.Bar(
    y=y_data,
    x=[100 - val for val in x_data],
    orientation='h',
    marker=dict(
        color='#E0E0E0',
        line=dict(width=0)
    ),
    width=0.4
))

# 布局优化
fig.update_layout(
    paper_bgcolor="rgba(0,0,0,0)",
    plot_bgcolor="rgba(0,0,0,0)",
    barmode='stack',
    showlegend=False,
    autosize=False,
    width=310,
    height=200,
    margin=dict(t=20, b=20, l=120, r=20)
)

# 轴设置
fig.update_yaxes(
    tickmode='array',
    tickvals=y_data,
    ticktext=y_data,
    tickfont=dict(size=12, color='#333'),
    showgrid=False
)
fig.update_xaxes(
    visible=False,
    range=[0, 100]
)

fig.show()

可选自定义标签方案

如果不想显示y轴,可改用自定义标注放置类别标签:

# 替换轴设置部分的y轴代码,添加如下annotations
annotations = []
for i, label in enumerate(y_data):
    annotations.append(dict(
        x=-10, y=i,
        text=label,
        font=dict(size=12, color='#333'),
        showarrow=False
    ))
fig.update_layout(annotations=annotations)
fig.update_yaxes(visible=False, showticklabels=False)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 12:35:02