1

Using example given on this page: ggplot inside function not working despite deparse(substitute , I tried to use aes_string but it is not working:

testfn <- function(gdf, first, second, third, fourth){
    print(
    ggplot(gdf, aes_string(first, second,
         color = fourth,
         linetype = third, 
         group = third:fourth))+
       geom_point()+
       geom_line() 
    )
}


> 
> testfn(phil, "Level", "value","Gender","Name")
Error in third:fourth : NA/NaN argument
In addition: Warning messages:
1: In aes_string(first, second, color = fourth, linetype = third, group = third:fourth) :
  NAs introduced by coercion
2: In aes_string(first, second, color = fourth, linetype = third, group = third:fourth) :
  NAs introduced by coercion
> 

Where is the problem. Thanks for your help.

Community
  • 1
  • 1
rnso
  • 23,686
  • 25
  • 112
  • 234
  • Is this a duplicate Q? – IRTFM May 01 '14 at 03:48
  • ggplot can't understand "third:fourth". if you're trying for interaction you need to do this (see Hadley's comment) http://stackoverflow.com/questions/15502263/ggplot-aes-string-with-interaction – infominer May 01 '14 at 03:50
  • and yes this seems very similar to the question you asked earlier? Thanks for pointing that out @BondedDust – infominer May 01 '14 at 03:51
  • Earlier question was for passing parameters to aes which was not working. Now I am trying to pass parameters to aes_string (though with the same data and function) and I am having problems. I am trying to follow the forum rules and giving all links. Thanks for your comments. – rnso May 01 '14 at 04:06
  • group = paste0("interaction(", paste0('"', third,":",fourth, '"', collapse = ", "), ")")))+ does not work. Error: attempt to apply non-function In addition: Warning message: In names(x)[!is.na(full)] <- .all_aesthetics[full[!is.na(full)]] : number of items to replace is not a multiple of replacement length – rnso May 01 '14 at 04:12

1 Answers1

4

First of all, in aes_string you need to use names for x and y [compare args(aes) and args(aes_string)]. And then the interaction term can be formulated more understandably as paste0("interaction(", third,", ",fourth, ")"). So together this gives

testfn <- function(gdf, first, second, third, fourth){
  p <- ggplot(gdf, aes_string(x = first, 
                              y = second,
                              color = fourth,
                              linetype = third,
                              group = paste0("interaction(", third,", ",fourth, ")"))) +
    geom_point() +
    geom_line() 
  print(p)
}
testfn(phil, "Level", "value","Gender","Name")
shadow
  • 21,823
  • 4
  • 63
  • 77