使用此页面上给出的示例: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
>
问题出在哪里。谢谢你的帮助。
答案 0 :(得分:3)
首先,在aes_string
中,您需要使用x
和y
[比较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")