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

如何解决Seaborn按hue分组的boxplot与stripplot散点X轴不对齐问题

你遇到的散点和箱线图不对齐的问题,是因为stripplot默认没有开启按hue分组偏移的配置,和boxplot的分组偏移逻辑不匹配,按以下方式调整即可:

  1. 核心调整:给stripplot添加dodge=True参数,这个参数会让散点按照hue分组做和箱线图一致的横向偏移,实现垂直对齐。
  2. 可选优化:
  • 调整jitter参数控制散点的横向抖动幅度,避免散点溢出箱体范围
  • 给stripplot添加legend=False参数,避免和boxplot的图例重复

修正后的完整代码如下:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy.random as rnd

f = plt.figure(figsize=[18,12])
ax = f.add_subplot(111)
sns.boxplot(x='month', y='ffdi', hue='scenario', data=df_diff_concat, ax=ax)
# 添加dodge=True实现按hue对齐,调整jitter控制抖动幅度,关闭重复图例
sns.stripplot(x="month", y="ffdi", hue='scenario', data=df_diff_concat, ax=ax, dodge=True, jitter=0.2, legend=False)
plt.show()

如果想要散点分布更均匀、无重叠,也可以把stripplot替换为swarmplot,同样添加dodge=True参数即可实现对齐效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 06:15:02