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

如何调整Seaborn分组箱线图的主组与子组间距

解决箱线图主分组与子分组的间距调整问题

问题说明

我有3个主分组(A、B、C),每个主分组下包含两个子分组(1和2)。希望绘制箱线图时,主分组之间的间距大于子分组的间距。原代码仅能调整x轴刻度标签,无法实现箱线图间距的对应对齐。

修改后的代码

import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

# 生成随机数据
FA_1 = np.random.randint(200, 230, 20)
FA_2 = np.random.randint(180, 210, 20)
FB_1 = np.random.randint(130, 160, 20)
FB_2 = np.random.randint(140, 170, 20)
FC_1 = np.random.randint(80, 110, 20)
FC_2 = np.random.randint(60, 90, 20)

# 构造DataFrame
data = [
    (FA_1, 'A_1'), (FA_2, 'A_2'),
    (FB_1, 'B_1'), (FB_2, 'B_2'),
    (FC_1, 'C_1'), (FC_2, 'C_2')
]
df = pd.DataFrame(data, columns=['Force', 'Config'])
df = df.explode('Force', ignore_index=True)
df['Force'] = df['Force'].astype(int)  # 转换数据类型,避免绘图警告

plt.figure(figsize=(10, 6))

# 手动设置每个子分组的位置,主分组间留更大间隔
pos_map = {
    'A_1': 0,
    'A_2': 1,
    'B_1': 3,  # 与A组间隔2个单位
    'B_2': 4,
    'C_1': 6,  # 与B组间隔2个单位
    'C_2': 7
}
# 给DataFrame添加位置列
df['pos'] = df['Config'].map(pos_map)

# 根据自定义位置绘制箱线图
sns.boxplot(x='pos', y='Force', data=df, width=0.4)

# 设置x轴刻度与标签
plt.xticks(
    ticks=list(pos_map.values()),
    labels=list(pos_map.keys())
)

plt.title('按配置分组的力值箱线图')
plt.xlabel('配置')
plt.ylabel('力值')
plt.tight_layout()
plt.show()

关键调整点

  • 自定义位置映射:给每个子分组分配x轴位置,主分组之间设置更大的间隔(比如A组到B组间隔2个单位,子分组之间间隔1个单位)
  • 关联位置列:在DataFrame中添加位置列,让Seaborn根据这个数值型的x轴位置绘图,而非默认的分类标签
  • 对齐刻度标签:手动指定xticks的ticks和labels,确保标签与箱线位置一一对应

内容的提问来源于stack exchange,提问作者A.E

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 05:07:29