如何解决Seaborn按hue分组的boxplot与stripplot散点X轴不对齐问题
你遇到的散点和箱线图不对齐的问题,是因为stripplot默认没有开启按hue分组偏移的配置,和boxplot的分组偏移逻辑不匹配,按以下方式调整即可:
- 核心调整:给
stripplot添加dodge=True参数,这个参数会让散点按照hue分组做和箱线图一致的横向偏移,实现垂直对齐。 - 可选优化:
- 调整
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
相关产品推荐
相关产品推荐

