【问题标题】:ggplot aes_string does not work inside a functionggplot aes_string 在函数内不起作用
【发布时间】:2014-06-17 13:49:41
【问题描述】:

使用此页面上给出的示例: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
> 

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

【问题讨论】:

  • 这是重复的 Q 吗?
  • ggplot 无法理解“第三:第四”。如果您正在尝试进行交互,则需要执行此操作(请参阅 Hadley 的评论)stackoverflow.com/questions/15502263/…
  • 是的,这似乎与您之前提出的问题非常相似?感谢您指出@BondedDust
  • 之前的问题是将参数传递给不起作用的 aes。现在我正在尝试将参数传递给 aes_string(尽管具有相同的数据和函数),但我遇到了问题。我正在尝试遵循论坛规则并提供所有链接。感谢您的 cmets。
  • group = paste0("interaction(", paste0('"', third,":",fourth, '"', collapse = ", "), ")")))+ 确实不行。错误:尝试应用非功能另外:警告消息:在名称(x)[!is.na(完整)]

标签: r ggplot2 parameter-passing


【解决方案1】:

首先,在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")

【讨论】:

  • 是的,它有效!这正是我所需要的。感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多