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

Python Plotly水平条形图如何将Y轴标签放置在分组条形上方

Plotly水平分组条形图标签调整方案

你需要调整以下3处配置即可实现需求:

  • 隐藏原生Y轴的刻度标签,避免和自定义标签冲突
  • 新增自定义注释模块,将原Y轴的分类文本作为注释添加到对应分组条形的上方位置
  • 可根据展示效果微调注释的坐标偏移、对齐方式和字体参数

修改后的完整代码如下:

import pandas as pd 
import plotly.graph_objects as go

test_df = pd.DataFrame({'component':['BAR 1','BAR 2','BAR 3'],'mean':[7.4,7.8,6.5],'mean_proj':[6.8,7.9,8.4]})

def barchart2(df,x1,x2,y):
    fig = go.Figure()
    fig.add_trace(go.Bar(name=x1,x=df[x1],y=df[y],orientation='h',hoverinfo=None,marker_color='#221435'))
    fig.add_trace(go.Bar(name=x2,x=df[x2],y=df[y],orientation='h',hoverinfo=None,marker_color='rgb(55,177,140)'))      
    fig.update_xaxes(showgrid=False, zeroline=False)
    # 隐藏Y轴默认刻度标签
    fig.update_yaxes(showgrid=False, zeroline=False, showticklabels=False)
    fig.update_layout(paper_bgcolor='rgba(0,0,0,0)',plot_bgcolor='rgba(0,0,0,0)',bargap=0.20,margin=dict(t=30,b=5,l=25,r=0))
    fig.update_layout(barmode='group')
    
    # 为每个分组添加顶部标签
    y_cats = df[y].tolist()
    for idx, cat in enumerate(y_cats):
        fig.add_annotation(
            x=0, # 标签X轴位置,可根据需求调整
            y=idx + 0.3, # 标签Y轴位置,0.3为偏移量,匹配分组条形的总高度
            text=cat,
            showarrow=False,
            xanchor='left',
            yanchor='bottom',
            font=dict(size=12)
        )
    
    return fig.write_html('test.html',auto_open=True)

barchart2(test_df,'mean','mean_proj','component')  

如果需要调整标签的位置,只需要修改x和y的偏移数值即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 22:15:03