计算标准误差并在 ggplot2 条形图上附加误差线

机器算法验证 r ggplot2 条形图
2022-04-11 06:19:45

给定一个最小的数据集,在其中寻找某个主题在 500 个观察值的数据集中的出现。with_motif 表示具有指定主题的观察,而 without_motif 是没有主题的观察。

with_motif <- 100
without_motif <- 400
dt <- data.frame(with_motif,without_motif)

以下代码将使用 ggplot2 库绘制条形图,

bar_plot <- ggplot(melt(dt),aes(variable,value)) + geom_bar() + scale_x_discrete(name="with or without") + theme_bw() + opts( panel.grid.major = theme_blank(),title = "", plot.title=theme_text(size=14))

bar_plot

我想计算 95% CI 的标准误差并将条形图附加到图上。ggplot 提供geom_errorbar(),但我很高兴知道得出标准误差(偏差)的不同方法,以便计算误差线限制(CI)。

1个回答

这是 ggplot2 主页的一个示例:https ://ggplot2.tidyverse.org/reference/geom_errorbarh.html正如其他人在评论中提到的那样,您必须自己计算 SE 并将此信息附加到 data.frame

df <- data.frame( 
  trt = factor(c(1, 1, 2, 2)), 
  resp = c(1, 5, 3, 4), 
  group = factor(c(1, 2, 1, 2)), 
  se = c(0.1, 0.3, 0.3, 0.2) 
 ) 
df2 <- df[c(1,3),]
p <- ggplot(df, aes(fill=group, y=resp, x=trt)) 
p + geom_bar(position="dodge", stat="identity") 
dodge <- position_dodge(width=0.9) 
p + geom_bar(position=dodge, stat="identity") + geom_errorbar(aes(ymax = resp + se, ymin=resp - se), position=dodge, width=0.25)  

作为一个指针,SE @ 95% CI 通常看起来像这样:

df$se <- 1.96*(sd(your_data, na.rm=T)/sqrt(your_n))

您的 CI 上限和下限将只是 df$se +/- 响应(如上面 geom_errorbar() 的 aes() 所示)