I have want to plot errorbars as well as text with my barchart. In order to make a nice and readable plot, I'd like the errorbars to be left (for the left bar) and right (for the right bar) of the geom_text
element. I would do this using position_dodge
but somehow this has no influence if the bars aren't grouped.
Here is my code:
df1 <- data.frame(e=c(0.02,0.02), na=c("A","B"), value=c(0.25, 0.75))
ggplot(df1, aes(x=factor(na), y=value, fill=factor(na)))+
geom_bar(stat="identity", width=0.2)+
geom_errorbar(aes(ymin = value-e, ymax = value+e), width = 0.01, size=0.5,
alpha=.6)+
geom_text(aes(label=paste0(round(value*100,0),"%"), vjust=-0.5),
size=5)
This produces the same plot:
ggplot(df1, aes(x=factor(na), y=value, fill=factor(na)))+
geom_bar(stat="identity", width=0.2)+
geom_errorbar(aes(ymin = value-e, ymax = value+e), width = 0.01, size=0.5,
alpha=.6, position=position_dodge(width=0.2))+
geom_text(aes(label=paste0(round(value*100,0),"%"), vjust=-0.5),
size=5)
How can I move my errorbars left/right?
Thanks
You can use the x aesthetic to specify the x position of the errorbars. Although the usual idiom to deal with this would be to keep the error bars centered, and shift the text (vertically preferably)
ggplot(df1, aes(x=factor(na), y=value, fill=factor(na)))+
geom_bar(stat="identity", width=0.2)+
geom_errorbar(aes(x = as.integer(factor(na)) +c(-0.1,0.1), ymin = value-e, ymax = value+e), width = 0.01, size=0.5,
alpha=.6)+
geom_text(aes(label=paste0(round(value*100,0),"%"), vjust=-0.5),
size=5)