Wrong position of errorbars using geom = "errorbars"

geom_errorbar position = dodge not working
geom error bar
change color of error bars ggplot
r horizontal error bars ggplot
geom_pointrange dodge
stat_summary error bars
error bars in r
add error bars to scatter plot ggplot2

I'm trying to add errorsbars to a graph I created:

As you can see the error bars are not in the right location and I can't figure out why not. The following is the code I used:

df_midtermclean$gender <- factor(df_midtermclean$ï..gender, labels = c('Male', 'Female'))  

#reshaping from wide to long format

data_long <- melt(df_midtermclean,
                  # ID variables - all the variables to keep but not split apart on
                  id.vars=c("gender"),
                  # The source columns
                  measure.vars=c("sSkills", "sPerform", "sComplex", "sIQ" ),
                  # Name of the destination column that will identify the original
                  # column that the measurement came from
                  variable.name="measures",
                  value.name="score")        

p2 <- ggplot(data_long, aes(measures, score)) + stat_summary(fun.y = mean, geom = "bar", aes(fill = gender), position = "dodge") 
    p2 <- p2 + stat_summary(geom = "errorbar", fun.data = mean_cl_normal, position = position_dodge(.9), width = .1)
    p2 <- p2 + labs(x = "Continuous Measures", y = "Participant Scores", fill = "Gender")
    p2

Data.

data_long <-
structure(list(gender = structure(c(1L, 1L, 1L, 
1L, 1L, 1L, 2L,  1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 
2L, 2L, 1L, 1L, 1L), .Label = c("Male",  "Female"), 
class = "factor"), measures = structure(c(1L, 1L,  
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L,  1L, 1L), .Label = c("sSkills", 
"sPerform", "sComplex", "sIQ"), class = "factor"), 
score = c(4.75, 3, 3.5, 3.75, 3, 3.25, 3.25, 3, 
2.75, 2.75, 2.5, 2.75, 3.75, 3.5, 3.75, 3.75, 
3.25, 3.25, 4, 3.25)), row.names = c(NA,  20L), 
class = "data.frame")

Unfortunatly your code is unreproducible ! However, I may be found a solution on http://www.sthda.com/english/wiki/ggplot2-error-bars-quick-start-guide-r-software-and-data-visualization

library(ggplot2)

df <- ToothGrowth
df$dose <- as.factor(df$dose)

# Function to calculate the mean and the standard deviation
data_summary <- function(data, varname, groupnames){
  require(plyr)
  summary_func <- function(x, col){
    c(mean = mean(x[[col]], na.rm=TRUE),
      sd = sd(x[[col]], na.rm=TRUE))
  }


 data_sum <- ddply(data, groupnames, .fun=summary_func, varname)
 data_sum <- rename(data_sum, c("mean" = varname))
 return(data_sum)
}

# New dataframe
df2 <- data_summary(ToothGrowth, varname="len", 
                    groupnames=c("supp", "dose"))

df2$dose <- as.factor(df2$dose)

ggplot(df2, aes(x=dose, y=len, fill=supp)) + 
  geom_bar(stat="identity", color="black", position=position_dodge()) +
  geom_errorbar(aes(ymin=len-sd, ymax=len+sd), width=.2, position=position_dodge(.9)) 

ggplot2 wrong position of error bars over the bars, It seems to be something with setting y as factor. If you remove it, it works: ggplot(​df, aes(x=ID, y=variable, fill=variable)) +  I think you can use dodging with real dates as long as you use the same dodge amount in geom_errorbar and geom_col.For example, in the following d sets the amount of dodging using 30.5 as the baseline width (the (more or less) average distance between months) and the factor of 0.9, applied to both the dodging and the width argument, gives the default bar widths.

I think the second line of your code should be of the following format:

 geom_errorbar(aes(ymin = lower, ymax = upper), position = dodge, width = 0.25)

I am not sure what stat_summary is in your code, can you explain that ? However, you need to explicitly mention the lower and upper bounds of the error bars, I don't think that is included in your code.

Edit: try tweaking the position=position=position_dodge(0.9), along with the size and widths.

geom_errorbar width incorrect when grouped and position dodged , geom_errorbar width incorrect when grouped and position dodged #1346 The value for the width of the error bars is being divided by the number of items grouped at the For reference I am using R 3.2.1 and ggplot2 1.0.1  position: Position adjustment, either as a string, or the result of a call to a position adjustment function. Other arguments passed on to layer(). These are often aesthetics, used to set an aesthetic to a fixed value, like colour = "red" or size = 3. They may also be parameters to the paired geom/stat. na.rm

I believe that something like the following will do what you want.

agg <- aggregate(score ~ gender + measures, data_long, function(x) c(mu = mean(x), se = sd(x)))
agg <- cbind(agg[-ncol(agg)], agg[[ncol(agg)]])

p2 <- ggplot(agg, aes(measures, mu, fill = gender, group = gender)) +
  geom_bar(stat = "identity", position = "dodge") +
  geom_errorbar(aes(ymin = mu - se, ymax = mu + se),
                position = position_dodge(0.9),
                width = 0.1)

p2

Wrong position of errorbars using geom = "errorbars", Wrong position of errorbars using geom = "errorbars". geom error bar geom_errorbar position = dodge not working change color of error bars ggplot r horizontal  # When using geom_errorbar () with position_dodge2 (), extra padding will be # needed between the error bars to keep them aligned with the bars. p + geom_col (position = "dodge2") + geom_errorbar (aes (ymin = lower, ymax = upper), position = position_dodge2 (width = 0.5, padding = 0.5))

Vertical intervals: lines, crossbars & errorbars, Source: R/geom-crossbar.r , R/geom-errorbar.r , R/geom-linerange.r , and 1 more geom_errorbar( mapping = NULL, data = NULL, stat = "identity", position = "​identity", If FALSE , the default, missing values are removed with a warning. # Standard error of the mean ggplot (tgc, aes (x = dose, y = len, colour = supp)) + geom_errorbar (aes (ymin = len-se, ymax = len + se), width =.1) + geom_line + geom_point # The errorbars overlapped, so use position_dodge to move them horizontally pd <-position_dodge (0.1) # move them .05 to the left and right ggplot (tgc, aes (x = dose, y = len, colour = supp)) + geom_errorbar (aes (ymin = len-se, ymax = len + se), width =.1, position = pd) + geom_line (position = pd) + geom_point

Horizontal error bars, Horizontal error bars A rotated version of geom_errorbar() . If specified and inherit.aes = TRUE (the default), it is combined with the default mapping at the top level of The statistical transformation to use on the data for this layer, as a string. position If FALSE , the default, missing values are removed with a warning. Note that, for line plot, you should always specify group = 1 in the aes(), when you have one group of line.

Plotting means and error bars (ggplot2), These are basic line and point graph with error bars representing either the position=pd) + geom_line(position=pd) + geom_point(position=pd) # Use 95% measurevar="value", groupvars="condition", na.rm=FALSE, conf.interval=.95)  The statistical transformation to use on the data for this layer, as a string. position Position adjustment, either as a string, or the result of a call to a position adjustment function. fatten A multiplicative factor used to increase the size of the middle bar in geom_crossbar() and the middle point in geom_pointrange(). na.rm

Comments
  • Can you post sample data? Please edit the question with the output of dput(data_long). Or, if it is too big with the output of dput(head(data_long, 20)).
  • I've added it :)
  • geom_errorbar() doesn't seem to be necessary according to this: stackoverflow.com/questions/44872951/…
  • try tweaking the position=position=position_dodge(0.9), along with the size and widths.