Search code examples
rggplot2

R error bar plot with side by side format


I want to create a side by side plot with error bar. I have sensitivity and specificity for each state. I also have upper bound and lower bound for each of the sensitivity and specificity. I want to draw a plot which shows the sensitivity/specificity with the upper and lower bound. My code is below. But it's not side by side. I want side by side like Side by Side R Barplot with error bars.

library("ggplot2")
data <- data.frame(x = c("AZ","AZ","CT","CT","IL","IL"),
                   sen_spe = c(rep(c("Sensitivity","Specificity"),3)),
                         y = runif(6, 0, 1),
                         lower = runif(6, 0, 0.1),
                         upper = runif(6, 0, 0.1))

data$lower <- data$y - data$lower
data$upper <- data$y + data$upper


ggplot(data, aes(x=x, y=y, color=sen_spe, fill=sen_spe)) + geom_point() + geom_errorbar(aes(ymin = lower, ymax = upper))  


Solution

  • To get your error bars (and the points) side by you have to tell ggplot2 to do so by using position = position_dodge(width = XXX) where the width determines by how much the error bars and points get dodged or shifted to the left/right:

    library(ggplot2)
    
    set.seed(123)
    
    ggplot(data, aes(x = x, y = y, color = sen_spe, fill = sen_spe)) +
      geom_point(position = position_dodge(width = .75)) +
      geom_errorbar(aes(ymin = lower, ymax = upper),
        position = position_dodge(width = .75), width = .45
      )
    

    enter image description here