如何让 geom_errorbar 在 ggplot2 的条形图上正确“闪避”?

rsa*_*ler 4 r ggplot2

我正在尝试制作带有误差线的分组条形图。但是,我无法使误差条看起来正确(即比主条更薄)并且位置正确(位于条的中心)。该position选项似乎position_dodge()无法正常工作,我无法弄清楚为什么——根据其他类似问题中的示例,这应该可以工作。

我正在 R 版本 3.4.2 中运行 ggplot2 版本 3.0.0。

一个最小的工作示例:

d<-data.frame(bin = factor(c(1,2,3,1,2,3)),type = factor(c(1,1,1,2,2,2)), beta = c(10,20,30,40,50,60), se = c(2,2,2,2,2,2))
ggplot(d, aes(x=bin,y=beta,ymin = beta - 1.96* se, ymax = beta+1.96* se)) + 
    geom_bar(aes(fill = type), position = position_dodge2(), stat="identity")  +
    geom_errorbar(position=position_dodge2(.9))
Run Code Online (Sandbox Code Playgroud)

生产:位置正确,太宽 位置正确,但太宽了。使用position_dodge()代替甚至position_dodge2()无法获得正确的位置:

ggplot(d, aes(x=bin,y=beta,ymin = beta - 1.96* se, ymax = beta+1.96* se)) + 
  geom_bar(aes(fill = type), position = position_dodge(), stat="identity")  +
  geom_errorbar(position=position_dodge(.9)) 
Run Code Online (Sandbox Code Playgroud)

更宽,而且位置错误 添加width参数来geom_errorbar破坏版本,position_dodge2()并且对版本没有帮助position_dodge():

ggplot(d, aes(x=bin,y=beta,ymin = beta - 1.96* se, ymax = beta+1.96* se)) + 
  geom_bar(aes(fill = type), position = position_dodge2(), stat="identity")  +
  geom_errorbar(position=position_dodge2(.9), width= .2)

ggplot(d, aes(x=bin,y=beta,ymin = beta - 1.96* se, ymax = beta+1.96* se)) + 
  geom_bar(aes(fill = type), position = position_dodge(), stat="identity")  +
  geom_errorbar(position=position_dodge(.9), width = .2) 
Run Code Online (Sandbox Code Playgroud)

宽度合适,位置错误 宽度不错,但位置仍然错误

这里发生了什么?我该如何解决?

aos*_*ith 9

如果您进入fill全球,aes()那么position_dodge()将按预期工作。group或者,您可以通过to添加分组变量geom_errorbar()。

ggplot(d, aes(x = bin, y = beta, 
              ymin = beta - 1.96*se, ymax = beta+1.96*se, fill = type)) + 
    geom_bar(position = position_dodge(), stat="identity")  +
    geom_errorbar(position=position_dodge(.9), width = .2)
Run Code Online (Sandbox Code Playgroud)

该问题position_dodge2()似乎是GitHub 问题中讨论的问题,可以通过参数解决padding。请注意,这种方法不再存在width争议。geom_errorbar()

ggplot(d, aes(x = bin, y = beta, 
              ymin = beta - 1.96*se, ymax = beta+1.96*se, fill = type)) + 
    geom_bar(position = position_dodge2(), stat="identity")  +
    geom_errorbar(position = position_dodge2(.9, padding = .6))
Run Code Online (Sandbox Code Playgroud)