Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
798 views
in Technique[技术] by (71.8m points)

r - ggplot aes_string does not work inside a function

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...