r - How to position both geom_path and geom_errorbar properly at the same time in ggplot2 -
i try create bar graph has both error bar , p_value.however, can't position both error bar , p_value bar properly. here 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 caused "fill" argument. if put "fill=b" in ggplot(), mess position of p_value bar. if put "fill=b" in geom_bar(), mess position of error bar.
add group=b
inside geom_errorbar
position_dodge
knows 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, can directly access positions of bars ggplot_build
## bar positions stuff <- ggplot_build(q) dat <- stuff[[1]][[2]]
Comments
Post a Comment