1

I wish to generate error bar for each data point in ggplot2 using a generic function that extracts column names for the same using the names function. Following is a demo code:

plotfn <- function(data, xind, yind, yerr) {
    yerrbar <- aes_string(ymin=names(data)[yind]-names(data)[yerr], ymin=names(data) [yind]+names(data)[yerr])
    p <- ggplot(data, aes_string(x=names(data)[xind], y=names(data)[yind]) + geom_point() + geom_errorbar(yerrbar)
    p
}

errdf <- data.frame('X'=rnorm(100, 2, 3), 'Y'=rnorm(100, 5, 6), 'eY'=rnorm(100))
plotfn(errdf, 1, 2, 3)

Running this gives the following error:

Error in names(data)[yind] - names(data)[yerr] : 
  non-numeric argument to binary operator

Any suggestions? Thanks.

tejas_kale
  • 593
  • 2
  • 7
  • 21

1 Answers1

9

You will need to pass a character string containing the - ('a-b' not 'a'-'b')

eg,

ggplot(mtcars,aes_string(y = 'mpg-disp',x = 'am')) + geom_point()

In your example

plotfn <- function(data, xind, yind, yerr) {
  # subset the names now so it is slightly less typing later
  yerr_names <- names(data)[c(yind,yerr)]

  yerrbar <- aes_string(ymin = paste(yerr_names, collapse = '-'), 
                         ymax = paste(yerr_names,collapse='+'))
   p <- ggplot(data, aes_string(x=names(data)[xind], y=names(data)[yind])) + 
     geom_point() + 
     geom_errorbar(mapping = yerrbar)
          p
}

# a slightly smaller, reproducible example
set.seed(1)
errdf <- data.frame('X'=rnorm(10, 2, 3), 'Y'=rnorm(10, 5, 6), 'eY'=rnorm(10))
plotfn(errdf, 1, 2, 3)

enter image description here

mnel
  • 113,303
  • 27
  • 265
  • 254