Labeling boxplot in seaborn with median value

2019-01-09 09:37发布

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?

1条回答
beautiful°
2楼-- · 2019-01-09 10:25

Can I just say that I love it when people include sample datasets. A healthy +1 to you!

import seaborn as sns, numpy as np

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

medians = tips.groupby(['day'])['total_bill'].median().values
median_labels = [str(np.round(s, 2)) for s in medians]

pos = range(len(medians))
for tick,label in zip(pos,ax.get_xticklabels()):
    ax.text(pos[tick], medians[tick] + 0.5, median_labels[tick], 
            horizontalalignment='center', size='x-small', color='w', weight='semibold')

enter image description here

查看更多
登录 后发表回答