Dr. Who
Dr. Who

Reputation: 141

How to position both geom_path and geom_errorbar properly at the same time in ggplot2

I try to create a bar graph that has both error bar and p_value.However, I can't position both error bar and p_value bar properly. Here is my code:

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)

The problem seems to be caused by the "fill" argument. If I put the "fill=b" in ggplot(), it mess up the position of the p_value bar. If I put the "fill=b" in geom_bar(), it mess up the position of error bar.

Upvotes: 2

Views: 322

Answers (1)

Rorschach
Rorschach

Reputation: 32436

Add group=b inside the geom_errorbar so the position_dodge knows what to do

  geom_errorbar(aes(ymin=c-err,ymax=c+err, group=b), width=0.3, lwd = 1, position=position_dodge(0.9))

For future reference, you can directly access the positions of the bars with ggplot_build

## Get bar positions
stuff <- ggplot_build(q)
dat <- stuff[[1]][[2]]

Upvotes: 2

Related Questions