Seaborn箱线图(Boxplot)与散点图(Stripplot)坐标轴对齐问题求助
解决Seaborn Boxplot与Stripplot坐标轴不对齐、箱线图不居中问题
我在可视化任务中遇到难题:绘制的Boxplot与Stripplot无法和坐标轴对齐,箱线图未与轴居中。尽管尝试了各类参数,仍找不到问题原因。
我的原代码:
plt.figure() ax =sns.boxplot(x="Station", y="MV (kg/m3)", data=DonneesLVL,hue='Sylviculture', order=[11,6,10,5,1], width=1) sns.stripplot(x="Station", y="MV (kg/m3)", data=DonneesLVL,hue='Sylviculture', ax=ax, dodge = True, jitter=True,order=[11,6,10,5,1]) handles, labels = ax.get_legend_handles_labels() l = plt.legend(handles[0:6], labels[0:6], fontsize=10) plt.ylabel('Masse volumique (kg/m3)') plt.savefig("MVLVL.png",dpi=300,bbox_inches="tight") plt.show()
问题效果:
问题原因
boxplot的width=1设置过大,导致每个Station刻度下的多组箱线图占满整个刻度宽度,无法居中,同时和stripplot的偏移逻辑冲突。- 未统一
boxplot和stripplot的dodge偏移参数,导致两者分组位置不匹配。
修改后的代码
import matplotlib.pyplot as plt import seaborn as sns plt.figure() # 调整箱线图宽度并显式设置偏移量,确保和散点图对齐 ax = sns.boxplot( x="Station", y="MV (kg/m3)", data=DonneesLVL, hue='Sylviculture', order=[11,6,10,5,1], width=0.6, # 缩小宽度,给分组留出分布空间 dodge=0.8 # 统一偏移逻辑,和散点图匹配 ) # 散点图保持dodge=True,与箱线图分组位置对应 sns.stripplot( x="Station", y="MV (kg/m3)", data=DonneesLVL, hue='Sylviculture', ax=ax, dodge=True, jitter=True, order=[11,6,10,5,1], size=4 # 可选:调整散点大小,避免拥挤 ) # 移除重复图例,重新创建清晰图例 ax.legend_.remove() handles, labels = ax.get_legend_handles_labels() plt.legend(handles[:len(set(DonneesLVL['Sylviculture']))], labels[:len(set(DonneesLVL['Sylviculture']))], fontsize=10) plt.ylabel('Masse volumique (kg/m3)') plt.savefig("MVLVL.png",dpi=300,bbox_inches="tight") plt.show()
关键修改点
- 缩小
boxplot的width:让每个Station下的分组箱线图有足够空间分布,避免占满刻度宽度导致不居中。 - 统一
dodge参数:给boxplot显式设置dodge=0.8,确保和stripplot的dodge=True使用一致的偏移逻辑,让散点与箱线图完全对齐。 - 优化图例处理:移除默认重复图例,根据实际类别数创建简洁图例,避免冗余。
内容的提问来源于stack exchange,提问作者Julien Vedrine
相关产品推荐
相关产品推荐

