【问题标题】:Display mean and deviation values on grouped boxplot in Python在 Python 中的分组箱线图上显示平均值和偏差值
【发布时间】:2019-10-07 11:27:04
【问题描述】:

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

我的代码是

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))

有人可以帮忙吗?

【问题讨论】:

  • 通过“上面”,你的意思是你想把平均值和标准重叠在中线的顶部还是把它们放在整个箱形图的上方,即最大值
  • 在整个箱形图之上,即最大值。
  • 你能帮忙@steven

标签: python seaborn boxplot annotate


【解决方案1】:

这个question 把我带到了这里,因为我也在寻找与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'
    )

此更改对我有用(尽管我只是想打印实际的中值)。您还可以添加更改,例如fontsizecolor 或样式(即weight),只需将它们作为参数添加到annotate

【讨论】:

    猜你喜欢
    • 2012-08-31
    • 2019-04-02
    • 2011-01-30
    • 1970-01-01
    • 2020-10-07
    • 2015-06-28
    • 2023-04-03
    • 2011-04-19
    相关资源
    最近更新 更多