如何按特定顺序重新排列箱线图文本

How to re-arrange the boxplot text in specific order

我正在尝试将文本放入我的箱线图中。但是,在我按特定顺序(高级、豪华、家庭)排列 x 轴后,数据标签不再遵循该顺序。我应该如何更改我的代码以反映该特定订单?

数据:

    RoomCategory    ADR
514 Superior    114.75
515 Family  372.88
516 Deluxe  182.5
517 Deluxe  300.0
518 Family  371.45
519 Family  320.0
520 Deluxe  300.0
521 Family  414.0

我的代码:

box_plot = sns.boxplot(data=bgr21, x='RoomCategory',y='ADR',order=['Superior','Deluxe','Family'])

# printing the median value in the boxplot
medians= bgr21.groupby(['RoomCategory'])['ADR'].median()
vertical_offset = bgr21['ADR'].median() * 0.05 # offset from median for display
round_medians = np.round(medians,2)

for xtick in box_plot.get_xticks():
    box_plot.text(xtick,round_medians[xtick] + vertical_offset,round_medians[xtick], 
           horizontalalignment='center', size='large',color='b',weight='semibold')

输出:

这个顺序不正确,是受我们指定类别顺序的影响。因此,我们需要重新排序要按预期顺序注释的中值数据。我使用类别的顺序对数据进行排序。

import seaborn as sns

sns.set_style("whitegrid")
tips = sns.load_dataset("tips")
box_plot = sns.boxplot(x="day",y="total_bill",data=tips, order=['Sun','Sat','Fri','Thur'])

medians = tips.groupby(['day'])['total_bill'].median()
medians = medians.reindex(index=['Sun','Sat','Fri','Thur'], copy=True)
#print(medians)
vertical_offset = tips['total_bill'].median() * 0.05 # offset from median for display

for i in range(len(box_plot.get_xticklabels())):
    #print(i)
    box_plot.text(i,medians[i] + vertical_offset,medians[i], 
            horizontalalignment='center',size='x-small',color='w',weight='semibold')