Deep Deep - 3 months ago 17
R Question

geom_errorbar upper for positive mean and lower for negative mean

I would like to plot error bars on my geom_bar plot. I know that you can adjust aes(ymax, ymin) to display only upper or only lower bars.

But, I have some negative and positive mean values for which I would like to show the error bars respectively.

Here is some sample code and data to play with

library(ggplot)
myData <- aggregate(mtcars$mpg,
by = list(cyl = mtcars$cyl, gears = mtcars$gear),
FUN = function(x) c(mean = mean(x), sd = sd(x),
n = length(x)))
myData <- do.call(data.frame, myData)
myData$se <- myData$x.sd / sqrt(myData$x.n)

colnames(myData) <- c("cyl", "gears", "mean", "sd", "n", "se")
myData$names <- c(paste(myData$cyl, "cyl /",
myData$gears, " gear"))

myData$sign <- c(1, -1, 1, 1, -1, 1, -1, 1)

myDataN <- mutate(myData, mean_new = mean*sign, se_new=se+30)
dodge <- position_dodge(width = 0.9)
limits <- aes(
ymax = myDataN$mean_new + myDataN$se_new,
ymin = myDataN$mean_new - myDataN$se_new)
#ymax = myDataN$mean_new, #for upper
#ymin = myDataN$mean_new) #for lower


p <- ggplot(data = myDataN, aes(x = names, y = mean_new, fill = names))

p + geom_bar(stat = "identity", position = dodge) +
geom_errorbar(limits, position = dodge, width = 0.25) +
theme(axis.text.x=element_blank(), axis.ticks.x=element_blank(),
axis.title.x=element_blank())


Thanks
-deep

jav jav
Answer

You can re-define the limits so that they are conditional on the mean_new (whether it is positive or negative):

limits <- aes(
  ymax = myDataN$mean_new + (myDataN$mean_new > 0)*myDataN$se_new,  
  ymin = myDataN$mean_new - (myDataN$mean_new < 0)*myDataN$se_new)

Given the above definition, you get the following plot:

enter image description here

It may be good to remove the whisker that touches the bar. However, I am unable to figure out how to do this at the moment.

Comments