python - 在 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))
有人可以帮忙吗?
解决方案
这个问题把我带到了这里,因为我也在寻找类似的解决方案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
.
推荐阅读
- java - Files.createDirectory() 真的是非阻塞的吗?
- php - 未捕获的 PDOException:即使存在扩展也找不到驱动程序
- javascript - Chrome控制台中的Javascript破坏
- webpack - 如何使用 webpackInclude 匹配多个动态 url 部分?
- python - 使用 ElementTree 解析 XML 时的“无”结果
- haskell - Haskell - 按最后一个元组元素对元组列表进行排序
- python - Pandas如何解析df.agg中name指定的函数
- maven - Gradle 创建 pom 失败
- java - 将 PHP curl 请求转换为 Java
- python - 如何将我的 python 字典转换为以下格式