Search code examples
rggplot2aesthetics

Error with aesthetics control


I've got the dataframe

pGi.Fi <- data.frame(
    Metadata_Well = c("D01", "F01"), 
    Freq = c("0.3789279","0.4191564"), 
    control = c("Scramble2","Scramble2"))

a vector for confidence interval CI <- c(0.03222640,0.03196117)

and this code for generate a barchart with error_bar

limits <- aes(ymax = Freq+CI, ymin = Freq-CI)
dodge <- position_dodge(width=0.9)
bp <- ggplot(data=pGi.Fi, aes(x=Metadata_Well, y=Freq, fill=control)) + 
    geom_bar(position = "dodge", stat="identity") + 
    geom_bar(position=dodge) + 
    geom_errorbar(limits, position=dodge, width=0.25) + 
    scale_fill_grey()

I've got this error

Aesthetics must either be length one, or the same length as the dataProblems:Metadata_Well, Freq

Thanks for your answer


Solution

  • Couldn't reproduce your error exactly, but I think that some of the problem has to do with the way you are passing your aesthetics in? Generally speaking it is preferable to reference variables on the data you pass to ggplot, rather than mixing some references to the data frame and others to variables in the local environment. I also dropped one of your geom_bar() calls as it appeared to be a duplicate.

    pGi.Fi <- data.frame(
        Metadata_Well = c("D01", "F01"), 
        Freq = c(0.3789279,0.4191564), 
        control = c("Scramble2","Scramble2"),
        ci = c(0.03222640,0.03196117)
    )
    
    dodge <- position_dodge(width=0.9)
    
    bp <- ggplot(
      data = pGi.Fi, 
      aes(
        x = Metadata_Well, 
        y = Freq, 
        fill = control
      )) + 
      geom_bar(
        position = "dodge", 
        stat = "identity"
      ) + 
      geom_errorbar(
        aes(
          ymax = Freq+CI, 
          ymin = Freq-CI
        ), 
        position = dodge, 
        width = 0.25
      ) + 
      scale_fill_grey()
    
    bp