r - ggplot2 - Error bars using a custom function -


i wish generate error bar each data point in ggplot2 using generic function extracts column names same using names function. following 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 gives following error:

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

any suggestions? thanks.

you need pass character string containing - ('a-b' not 'a'-'b')

eg,

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

in example

plotfn <- function(data, xind, yind, yerr) {   # subset names 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 }  # 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


Comments

Popular posts from this blog

java - JavaFX 2 slider labelFormatter not being used -

Detect support for Shoutcast ICY MP3 without navigator.userAgent in Firefox? -

web - SVG not rendering properly in Firefox -