如何使用geom_errorbar在堆叠条形图中堆叠误差条?

raf*_*ira 3 r ggplot2

我想使用 geom_errorbar / ggplot 在堆叠的直方图中堆叠误差线。

在我的 ggplot 声明中,我尝试同时使用position="stack"position="identity"。他们都没有工作。

这是我的 ggplot 声明:

ggplot(DF, aes(x=factor(year), y=proportion, fill=response)) +
        facet_grid(. ~ sex) +
        theme(legend.position="none")
        geom_bar(position="stack", stat="identity") +
        geom_errorbar(aes(ymin=ci_l, ymax=ci_u),
                      width=.2,                    # Width of the error bars
                      position="identity") +
Run Code Online (Sandbox Code Playgroud)

这是我得到的结果,您可能会注意到右侧的误差条不遵循条形值。

在此处输入图片说明

这是我在此示例中使用的数据框:

DF <- data.frame(sex=c("men","women","men","women","men","women"),
                  proportion=c(0.33,0.32,0.24,0.29,0.12,0.16),
                  ci_l=c(0.325,0.322,0.230,0.284,0.114,0.155),
                  ci_u=c(0.339,0.316,0.252,0.311,0.130,0.176),
                  year=c(2008,2008,2013,2013,2013,2013),
                  response=c("Yes","Yes","Yes, entire the journey","Yes, entire the journey","Yes, part of the journey","Yes, part of the journey")
                  )
Run Code Online (Sandbox Code Playgroud)

Car*_*lli 6

这里发生的事情ggplot是没有堆叠误差条(它们必须相加),所以你必须手动完成(哈德利似乎认为这不是一个好主意,不会添加这个功能) .

所以手工做:

DF$ci_l[DF$response == "Yes, part of the journey"] <- with(DF,ci_l[response == "Yes, part of the journey"] +
         ci_l[response == "Yes, entire the journey"])

DF$ci_u[DF$response == "Yes, part of the journey"] <- with(DF,ci_u[response == "Yes, part of the journey"] +
                                                             ci_u[response == "Yes, entire the journey"])
Run Code Online (Sandbox Code Playgroud)

现在:

ggplot(DF, aes(x=factor(year), y=proportion)) +
  facet_grid(. ~ sex) +
  geom_bar(stat="identity",aes(fill=response)) +
  geom_errorbar(aes(ymin= ci_l, 
                    ymax= ci_u),
                width=.2,                    # Width of the error bars
                position="identity")
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明