ggplot aes_string does not work inside a function

依然范特西╮ 提交于 2019-12-17 21:15:28

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/23401681/ggplot-aes-string-does-not-work-inside-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!