如何绘制X轴分组不重叠的多箱线图(含双Y轴)
解决多箱线图双Y轴错位问题
问题说明
需要绘制三组箱线图:
- Group 1 数值量级大,放在X轴最左侧,使用左侧Y轴
- Group 2、Group 3 依次放在X轴右侧,使用右侧Y轴
- X轴顺序必须严格为
Group 1 → Group 2 → Group 3
使用ax.twinx()时出现分组位置重叠、Group 3位置错误的问题。
修正代码
import seaborn as sns import matplotlib.pyplot as plt import pandas as pd # 构造数据 df_plot = pd.DataFrame( [[0, 10], [0, 10.1], [0, 9.8], [1, 0.4], [1, 0.2], [1, 0.9], [2, 1.2], [2, 0.2], [2, 1]], columns=["x", "y"] ) x_labels = ["Group 1", "Group 2", "Group 3"] # 给每个分组指定X轴位置,确保顺序正确 x_positions = [0, 1, 2] fig, ax1 = plt.subplots(figsize=(2560/120, 1335/120)) # 在左轴绘制Group 1,指定X位置为0 sns.boxplot( data=df_plot[df_plot["x"] == 0], x=[x_positions[0]]*len(df_plot[df_plot["x"] == 0]), # 强制指定X位置 y="y", ax=ax1 ) ax1.set_ylabel("Y level", fontsize=22) ax1.tick_params(axis='both', labelsize=16) # 创建右轴 ax2 = ax1.twinx() # 在右轴绘制Group 2和Group 3,指定对应的X位置 sns.boxplot( data=df_plot[df_plot["x"] > 0], x=[x_positions[1]]*len(df_plot[df_plot["x"] == 1]) + [x_positions[2]]*len(df_plot[df_plot["x"] == 2]), y="y", ax=ax2 ) ax2.set_ylabel("Y level (Group 2/3)", fontsize=22) ax2.tick_params(axis='y', labelsize=16) # 统一设置X轴刻度和标签,确保两个轴对齐 ax1.set_xlabel("Buckets", fontsize=22) ax1.set_xticks(x_positions) ax1.set_xticklabels(x_labels, fontsize=16) # 隐藏右轴的X刻度,避免重复 ax2.set_xticks([]) plt.grid() plt.show() plt.close()
关键修正点
- 强制指定X位置:不再依赖原始数据中的
x值,手动给每个分组分配X轴位置(0、1、2),确保三个箱线图在X轴上依次排列,不会重叠 - 对齐X轴刻度:仅在左轴设置X轴的刻度和标签,右轴隐藏X刻度,避免双轴刻度冲突
- 分离双轴数据:明确在左轴绘制Group1,右轴绘制Group2和Group3,避免数据混淆
内容的提问来源于stack exchange,提问作者swissy
相关产品推荐
相关产品推荐

