ggplot aes_string在函数内部不起作用

时间:2014-05-01 03:43:18

标签: r ggplot2 parameter-passing

使用此页面上给出的示例:ggplot inside function not working despite deparse(substitute,我尝试使用aes_string但它不起作用:

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
> 

问题出在哪里。谢谢你的帮助。

1 个答案:

答案 0 :(得分:3)

首先,在aes_string中,您需要使用xy [比较args(aes)args(aes_string)]的名称。然后,交互项可以更容易理解为paste0("interaction(", third,", ",fourth, ")")。所以这一起给出了

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