简体   繁体   中英

function with ggplot and aes_

I just read hadley's article: http://rpubs.com/hadley/97970 Really cool!

Because of that I want to prepare some simple function. When I want to create a plot and use one more variable to distinguish all objects we generally use color or fill parameter. I always have a problem to remember that I should use color parameter in scatterplot and fill in eg boxplot. Therefore, when I do not use color parameter I want to use red color default:

point <- function(data, x, y, color = NULL){
  if (is.null(color)){
    ggplot(data, aes_(x = substitute(x),y = substitute(y)))+
      geom_point(color = 'red')
    }
  else{
    ggplot(data, aes_(x = substitute(x),y = substitute(y),color = substitute(color)))+
      geom_point()
}
}

In this case, point(mtcars, qsec, mpg) works correctly but function with color parameter does not work at all - point(mtcars, qsec, mpg, factor(cyl)) . Why?

It seems you have a problem with non-standard evaluation. When you run is.null() on color , you are evaluating the promise that's passed to the function. This then changes the behavior of calling substitute() on the variable. The behavior you are trying to get by using substitute() relies on being passed an un-evaluated promise. For example

foo<-function(x=NULL) {
   if(is.null(x)) {
       "NOTPASSED"
   } else {
       substitute(x)
   }
}

foo()
#[1] "NOTPASSED"
foo(ok)
# Error in foo(ok) : object 'ok' not found

The is.null sends R looking for a variable named ok which is not found. You want to be able to extract just the name of the variable and not the value.

In this case you are really just checking for missing parameters. it would be better to use missing() . Compare to

foo<-function(x) {
   if(missing(x)) {
       "NOTPASSED"
   } else {
       substitute(x)
   }
}

foo()
# [1] "NOTPASSED"
foo(ok)
# ok

The missing() function will not attempt to evaluate the promise. You can adapt this for your own function. It's really not specific to ggplot .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM