Labeling boxplot in seaborn with median value

user308827 picture user308827 · Jul 29, 2016 · Viewed 24k times · Source

How can I label each boxplot in a seaborn plot with the median value?

E.g.

import seaborn as sns
sns.set_style("whitegrid")
tips = sns.load_dataset("tips")
ax = sns.boxplot(x="day", y="total_bill", data=tips)

How do I label each boxplot with the median or average value?

Answer

mechanical_meat picture mechanical_meat · Jul 29, 2016

I love when people include sample datasets!

import seaborn as sns

sns.set_style("whitegrid")
tips = sns.load_dataset("tips")
box_plot = sns.boxplot(x="day",y="total_bill",data=tips)

medians = tips.groupby(['day'])['total_bill'].median()
vertical_offset = tips['total_bill'].median() * 0.05 # offset from median for display

for xtick in box_plot.get_xticks():
    box_plot.text(xtick,medians[xtick] + vertical_offset,medians[xtick], 
            horizontalalignment='center',size='x-small',color='w',weight='semibold')

enter image description here