如何在seaborn分组箱线图上标注另一组对应类别的中位数标记
解决方案
你原来的标注逻辑是把中位数直接标在X轴主刻度(每个Model对应的中心位置),没有考虑分组下不同Method的箱线的水平偏移。只需要替换原代码中中位数计算和标注的部分即可实现精准匹配,修改逻辑如下:
- 按
Model和Method分组计算两类数据的中位数,顺序和箱线渲染顺序完全一致 - 从坐标轴的
patches属性获取所有箱线对象,取每个箱线的水平中心作为标注点的X坐标
完整修改后的代码
import seaborn as sns import pandas as pd import matplotlib.pyplot as plt import numpy as np sns.set_theme(style='ticks', palette='pastel') fig = plt.figure(figsize=(15,5)) fig.subplots_adjust(hspace=0.12, wspace=0.15, right=0.98, left=0.12, bottom=0.15, top=0.98) plt.rcParams['text.usetex'] = False plt.rcParams['axes.labelsize'] = 12 plt.rcParams['font.size'] = 11 plt.rcParams['legend.fontsize'] = 12 plt.rcParams['xtick.labelsize'] = 11 plt.rcParams['ytick.labelsize'] = 11 ax1 = fig.add_subplot(1,2,1) ax2 = fig.add_subplot(1,2,2) def grouped_boxplot(axis_type1, axis_type2): methods = ['m1', 'm2', 'm3', 'm4', 'm5', 'm6', 'm7'] df_model1_type1 = pd.DataFrame() df_model1_type2 = pd.DataFrame() df_model2_type1 = pd.DataFrame() df_model2_type2 = pd.DataFrame() df_model3_type1 = pd.DataFrame() df_model3_type2 = pd.DataFrame() df_model4_type1 = pd.DataFrame() df_model4_type2 = pd.DataFrame() for m in methods: df_model1_type1[m] = np.random.randint(1,101,10) df_model1_type2[m] = np.random.randint(1,101,10) for m in methods: df_model2_type1[m] = np.random.randint(1,101,10) df_model2_type2[m] = np.random.randint(1,101,10) for m in methods: df_model3_type1[m] = np.random.randint(1,101,10) df_model3_type2[m] = np.random.randint(1,101,10) for m in methods: df_model4_type1[m] = np.random.randint(1,101,10) df_model4_type2[m] = np.random.randint(1,101,10) df_model1_type1 = df_model1_type1.assign(Model='model1') df_model1_type2 = df_model1_type2.assign(Model='model1') df_model2_type1 = df_model2_type1.assign(Model='model2') df_model2_type2 = df_model2_type2.assign(Model='model2') df_model3_type1 = df_model3_type1.assign(Model='model3') df_model3_type2 = df_model3_type2.assign(Model='model3') df_model4_type1 = df_model4_type1.assign(Model='model4') df_model4_type2 = df_model4_type2.assign(Model='model4') df_type1 = pd.concat([df_model1_type1,df_model2_type1,df_model3_type1, df_model4_type1]) df_type2 = pd.concat([df_model1_type2,df_model2_type2,df_model3_type2, df_model4_type2]) df_type1_long = pd.melt(df_type1, 'Model', var_name='Method', value_name='var') df_type2_long = pd.melt(df_type2, 'Model', var_name='Method', value_name='var') axis_type1 = sns.boxplot(x='Model', hue='Method', y='var', data=df_type1_long, showfliers=False, whis=0, ax=axis_type1) axis_type2 = sns.boxplot(x='Model', hue='Method', y='var', data=df_type2_long, showfliers=False, whis=0, ax=axis_type2) # -------------------------- 以下为修改部分 -------------------------- # 按Model+Method分组计算中位数,顺序和箱线顺序完全匹配 type2_median = df_type2_long.groupby(['Model', 'Method'], sort=False)['var'].median().values type1_median = df_type1_long.groupby(['Model', 'Method'], sort=False)['var'].median().values # 标注type2中位数到type1的对应箱线 for patch, med in zip(axis_type1.patches, type2_median): # 取箱线中心x坐标 x = patch.get_x() + patch.get_width() / 2 axis_type1.scatter(x, med, s=20, marker='*', color='red', zorder=10) # 标注type1中位数到type2的对应箱线 for patch, med in zip(axis_type2.patches, type1_median): x = patch.get_x() + patch.get_width() / 2 axis_type2.scatter(x, med, s=20, marker='*', color='red', zorder=10) # -------------------------- 修改部分结束 -------------------------- axis_type1.legend([],[], frameon=False) axis_type2.legend(loc='lower center', bbox_to_anchor=(-0.2,-0.25), ncol=7) grouped_boxplot(ax1, ax2) plt.show() # plt.savefig('the_ultimate_boxplot.pdf')
代码中增加了zorder=10保证标注的红星显示在箱线上方不会被遮挡。
内容的提问来源于stack exchange,提问作者scriptgirl_3000
相关产品推荐
相关产品推荐

