如何在 ggplot2 (R) 中绘制多组均值和置信区间?

How to plot multiple group means and the confidence intervals in ggplot2 (R)?

我有这样的数据:

A  B  C
8  5  2
9  3  1
1  2  3
3  1  2
4  3  1

我需要使用 ggplot2 绘制每一个的均值以及置信区间。我还想从数据本身推导出置信区间(例如,使用 stat_summary(fun.data = mean_cl),但是我不确定如何绘制数据的均值这种格式。

我尝试了以下代码,但它没有 运行。我不确定第 2 行的 y 中需要输入什么。

pd <- position_dodge(0.78)
ggplot(dat, y = c(dat$A,dat$B,dat$C) + ylim(0,10) + theme_bw()) + 
  stat_summary(geom="bar", fun.y=mean, position = "dodge") + 
  stat_summary(geom="errorbar", fun.data=mean_cl_normal, position = pd)

我收到以下错误:

Warning messages:
1: Computation failed in `stat_summary()`:
object 'x' not found 
2: Computation failed in `stat_summary()`:
object 'x' not found

您的数据不是长格式,这意味着它应该如下所示:

thing<-data.frame(Group=factor(rep(c("A","B","C"),5)),
                  Y = c(8,9,1,3,4, 
                        5,3,2,1,3,
                        2,1,3,2,1)
                  )

您可以使用 melt() 之类的函数来帮助获取 reshape2 包中的数据格式。

完成后,您还必须计算数据的均值和 SE(在 ggplot 之前手动计算,或在 ggplot 中通过 stat_summary 中的正确表达式计算) .您可能从示例中得到 copied/pasted,因为您正在使用的函数(例如,mean_cl_normal)可能未定义。

那就动手吧

library(plyr)

cdata <- ddply(thing, "Group", summarise,
               N    = length(Y),
               mean = mean(Y),
               sd   = sd(Y),
               se   = sd / sqrt(N)
)
cdata

#Group N mean       sd       se
#1     A 5  4.0 2.236068 1.000000
#2     B 5  3.8 3.033150 1.356466
#3     C 5  1.8 1.788854 0.800000

现在您可以使用 ggplot.

pd <- position_dodge(0.78)

ggplot(cdata, aes(x=Group, y = mean, group = Group)) +
   #draws the means
      geom_point(position=pd) +
   #draws the CI error bars
      geom_errorbar(data=cdata, aes(ymin=mean-2*se, ymax=mean+2*se, 
      color=Group), width=.1, position=pd)

这给出了附图。

就像大卫说的,你首先需要长格式,但你应该能够使用 fun.data = "mean_cl_normal" 或像这样插入各种其他格式:

library(tidyr); library(ggplot2)
dat <- gather(dat) # gather to long form

ggplot(data = dat, aes(x = key, y = value)) +
    geom_point(size = 4, alpha = .5) + # always plot the raw data
    stat_summary(fun.data = "mean_cl_normal", geom = "crossbar") +
    labs(title = "95% Mean Confidence Intervals")

如果您想手动构建相同的时间间隔,您只需要 lmconfint 即可获得您想要的信息:

mod <- lm(value ~ 0 + key, data = dat)
ci <- confint(mod)