首页 > 解决方案 > 在 Python 中的分组箱线图上显示平均值和偏差值

问题描述

我想在分组箱线图中的每个箱线图上方显示平均值和标准偏差值(见图)。分组图

我的代码是

import pandas as pd
import seaborn as sns
from os.path import expanduser as ospath

df = pd.read_excel(ospath('~/Documents/Python/Kandidatspeciale/TestData.xlsx'),'Ark1')

bp = sns.boxplot(y='throw angle', x='incident angle', 
                 data=df, 
                 palette="colorblind",
                 hue='Bat type')

bp.set_title('Rubber Comparison',fontsize=15,fontweight='bold', y=1.06)
bp.set_ylabel('Throw Angle [degrees]',fontsize=11.5)
bp.set_xlabel('Incident Angle [degrees]',fontsize=11.5)

我的数据框df在哪里

    Bat type  incident angle  throw angle
0      euro              15         28.2
1      euro              15         27.5
2      euro              15         26.2
3      euro              15         27.7
4      euro              15         26.4
5      euro              15         29.0
6      euro              30         12.5
7      euro              30         14.7
8      euro              30         10.2
9     china              15         29.9
10    china              15         31.1
11    china              15         24.9
12    china              15         27.5
13    china              15         31.2
14    china              15         24.4
15    china              30          9.7
16    china              30          9.1
17    china              30          9.5

我尝试使用以下代码。它需要独立于 x(入射角)的数量,例如它应该为 45、60 等更多的角度工作。

m=df.mean(axis=0) #Mean values 
st=df.std(axis=0) #Standard deviation values 

for i, line in enumerate(bp['medians']):
    x, y = line.get_xydata()[1]
    text = ' μ={:.2f}\n σ={:.2f}'.format(m[i], st[i])
    bp.annotate(text, xy=(x, y))

有人可以帮忙吗?

标签: pythonseabornboxplotannotate

解决方案


这个问题把我带到了这里,因为我也在寻找类似的解决方案seaborn

经过反复试验,您只需将其更改for loop为:

for i in range(len(m)):
    bp.annotate(
        ' μ={:.2f}\n σ={:.2f}'.format(m[i], st[i]), 
        xy=(i, m[i]), 
        horizontalalignment='center'
    )

这个改变对我有用(虽然我只是想打印实际的中值)。您还可以添加更改,如fontsize,color或样式(即weight),只需将它们作为参数添加到annotate.


推荐阅读