ggboxplot误差线疑问:误差类型及添加标准差误差线方法
ggboxplot:bxp.errorbar参数含义与标准差误差线添加方法
一、bxp.errorbar=TRUE生成的误差线是什么?
当你给ggboxplot()加上bxp.errorbar = TRUE时,出现的误差线本质是箱线图须(whiskers)的另一种显示形式,它对应的范围和默认箱线图的须完全一致:上边界是第三四分位数(Q3)加1.5倍四分位距(IQR),下边界是第一四分位数(Q1)减1.5倍IQR。这个范围和置信区间、标准差、标准误都没关系,就是箱线图原生的极值范围。
二、怎么添加标准差误差线?
因为ggboxplot是基于ggplot2封装的,要加标准差误差线,有两种实用方法:
方法1:先统计分组的均值和标准差,再叠加误差线
先用dplyr按你的分组变量(Group和Type)计算每个组的均值和标准差:
library(dplyr) summary_stats <- AllLiveNaiveFIULearnedPanamaAnalysisNoOutliers %>% group_by(Group, Type) %>% summarise( avg_time = mean(Seconds_Fixed, na.rm = TRUE), sd_time = sd(Seconds_Fixed, na.rm = TRUE), .groups = "drop" )
然后在原箱线图代码后叠加geom_errorbar:
ggboxplot(AllLiveNaiveFIULearnedPanamaAnalysisNoOutliers, x = "Group", y = "Seconds_Fixed", fill = "grey40", ylab = "Time (seconds)", xlab = "Quadrant", color = "Type", ylim = c(0, 6500)) + geom_errorbar(data = summary_stats, aes(x = Group, ymin = avg_time - sd_time, ymax = avg_time + sd_time, color = Type), width = 0.2) # width控制误差线两端的短横线长度
方法2:用stat_summary自动计算并添加
不需要提前统计,直接用stat_summary让ggplot自动计算每个组的均值和标准差,然后生成误差线:
ggboxplot(AllLiveNaiveFIULearnedPanamaAnalysisNoOutliers, x = "Group", y = "Seconds_Fixed", fill = "grey40", ylab = "Time (seconds)", xlab = "Quadrant", color = "Type", ylim = c(0, 6500)) + stat_summary( fun.data = function(x) { m <- mean(x, na.rm = TRUE) s <- sd(x, na.rm = TRUE) data.frame(y = m, ymin = m - s, ymax = m + s) }, aes(color = Type), geom = "errorbar", width = 0.2 )
如果需要在误差线中间显示均值点,可以再加一层stat_summary:
# 在上面的代码后继续添加 stat_summary( fun = mean, aes(color = Type), geom = "point", size = 2 # 控制点的大小 )
内容的提问来源于stack exchange,提问作者user25994427
相关产品推荐
相关产品推荐

