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

如何用Plotly Python绘制多层堆叠X轴箱线图?

实现Plotly多级堆叠X轴箱线图

要实现三级及以上的堆叠X轴箱线图,你可以通过底层X轴绑定最细粒度分类,再用annotations添加上层分组标签的方式来实现,以下是具体代码和说明:

示例代码

import pandas as pd
import plotly.graph_objects as go

# 替换为你的实际数据
data = {
    'Level1': ['Group A']*6 + ['Group B']*6,
    'Level2': ['Subgroup A1']*3 + ['Subgroup A2']*3 + ['Subgroup B1']*3 + ['Subgroup B2']*3,
    'Level3': ['Cat1', 'Cat2', 'Cat3']*4,
    'y_value': [12,15,13, 9,11,10, 18,20,19, 14,16,15]
}
df1 = pd.DataFrame(data)

# 为每个箱线分配唯一的X位置,确保同组排列
df1['x_pos'] = pd.factorize(df1['Level2'] + '_' + df1['Level3'])[0]
unique_x = df1['x_pos'].unique()

# 创建箱线图轨迹
img1 = go.Figure()
for idx, (group, sub_df) in enumerate(df1.groupby(['Level2', 'Level3'])):
    img1.add_trace(go.Box(
        x=[idx],
        y=sub_df['y_value'],
        showlegend=False
    ))

# 设置最底层X轴(Level3)
img1.update_xaxes(
    tickmode='array',
    tickvals=unique_x,
    ticktext=df1['Level3'].unique(),
    title_text='Level 3'
)

# 添加Level2分组标签
level2_groups = df1.groupby('Level2')['x_pos'].agg(['min', 'max'])
for label, (min_x, max_x) in level2_groups.iterrows():
    img1.add_annotation(
        x=(min_x + max_x)/2,
        y=-0.15,
        text=label,
        showarrow=False,
        xref='x',
        yref='paper',
        font=dict(size=12)
    )

# 添加Level1分组标签(最上层)
level1_groups = df1.groupby('Level1')['x_pos'].agg(['min', 'max'])
for label, (min_x, max_x) in level1_groups.iterrows():
    img1.add_annotation(
        x=(min_x + max_x)/2,
        y=-0.25,
        text=label,
        showarrow=False,
        xref='x',
        yref='paper',
        font=dict(size=14, weight='bold')
    )

# 调整布局,预留底部空间放置多层标签
img1.update_layout(
    yaxis_title='y_value',
    margin=dict(b=100),
    height=500
)

img1.show()

关键说明

  1. X位置分配:用pd.factorize为每个Level2+Level3的组合分配唯一位置,确保同组箱线连续排列。
  2. 上层标签添加:通过annotations实现多级分组标签,利用yref='paper'固定标签在X轴下方的相对位置,通过计算分组的最小/最大X位置平均值,让标签居中对齐对应分组。
  3. 布局调整:增大底部边距margin(b),避免上层标签被截断。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 11:31:07