如何在ggplot2中同时正确定位geom_路径和geom_errorbar

如何在ggplot2中同时正确定位geom_路径和geom_errorbar,r,ggplot2,R,Ggplot2,我尝试创建一个同时具有错误条和p_值的条形图。但是,我无法正确定位错误条和p_值条。这是我的密码: library(ggplot2) df = data.frame(a=c('A','A','B','B'),b=c('X','Y','X','Y'),c=c(1,2,3,2),err=c(.1,.2,.1,.2)) q = ggplot(df, aes(a, y=c))+ geom_bar(aes(fill=b),position=position_dodge(), stat="identit

我尝试创建一个同时具有错误条和p_值的条形图。但是,我无法正确定位错误条和p_值条。这是我的密码:

library(ggplot2)
df = data.frame(a=c('A','A','B','B'),b=c('X','Y','X','Y'),c=c(1,2,3,2),err=c(.1,.2,.1,.2))
q = ggplot(df, aes(a, y=c))+
  geom_bar(aes(fill=b),position=position_dodge(), stat="identity")+
  geom_errorbar(aes(ymin=c-err,ymax=c+err), width=0.3, lwd = 1, position=position_dodge(0.9))


path = data.frame(x=c(1.25,1.75),y=c(3.5,3.5))
q = q + geom_path(data=path,aes(x=x, y=y),size=2)
q = q+ annotate('text',x=1.5,y=4, label='p=0.03')

print(q)

这个问题似乎是由“填充”论点引起的。如果我把“fill=b”放在ggplot()中,它会弄乱p_值条的位置。如果我把“fill=b”放在geom_bar()中,它会弄乱错误条的位置

group=b
添加到
geom\u errorbar
中,以便
位置闪避
知道该做什么

  geom_errorbar(aes(ymin=c-err,ymax=c+err, group=b), width=0.3, lwd = 1, position=position_dodge(0.9))
为了便于将来参考,您可以使用
ggplot\u build

## Get bar positions
stuff <- ggplot_build(q)
dat <- stuff[[1]][[2]]
##获取条形图位置

谢谢,它成功了!GGU的构建建议非常棒。