我想编写一个函数,用于在 ggplot 中进行美学映射。该函数应该有两个参数:
然而,我想要的是在 geom_point 函数中进行映射,而不是在初始的 ggplot 函数内进行映射。这时会收到以下错误信息:
错误:
如果将参数 aesthetic 作为带有
var
应该映射到 aesthetic
。下面的第一个代码块实际上可以工作。然而,我想要的是在 geom_point 函数中进行映射,而不是在初始的 ggplot 函数内进行映射。这时会收到以下错误信息:
错误:
:=
只能在准引用的参数内使用library(ggplot2)
myfct <- function(aesthetic, var){
aesthetic <- enquo(aesthetic)
var <- enquo(var)
ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, !! (aesthetic) := !!var)) +
geom_point()
}
myfct(size, Petal.Width)
2. 块(Block):抛出错误
library(ggplot2)
myfct <- function(aesthetic, var){
aesthetic <- enquo(aesthetic)
var <- enquo(var)
ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) +
geom_point(aes(!! (aesthetic) := !!var))
}
myfct(size, Petal.Width)
如果将参数 aesthetic 作为带有
sym
的字符串传递,也会出现相同的行为。# 1. block
myfct <- function(aesthetic, var){
aesthetic <- sym(aesthetic)
ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, !! aesthetic := {{var}})) +
geom_point()
}
myfct("size", Petal.Width)
# works
# 2. block
myfct <- function(aesthetic, var){
aesthetic <- sym(aesthetic)
ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) +
geom_point(aes(!! aesthetic := {{var}}))
}
myfct("size", Petal.Width)
# doesn't work
geom_point()
中的aes()
为什么会继承ggplot
调用中的x
和y
参数,而在函数上下文中却没有这种情况发生。 - TimTeaFanx
和y
。似乎更多是:=
的 NSE 问题。如果我们只使用左手边的 NSE,即size = !! var
,一切都正常:`testaes <- function(aesthetic, var){ aesthetic <- enquo(aesthetic) var <- enquo(var) print("with x and y:") print(aes(Sepal.Length,Sepal.Width,!!(aesthetic) := !!var)) print("without x and y and LHS NSE:") print(aes(!!(aesthetic) := !!var)) print("without x and y and only RHS NSE:") print(aes(size = !!var))} ` - TimTeaFan:=
时,x
和y
是问题的根源; 当占据命名参数的位置时,似乎:=
无效。在你的例子中,它之所以起作用,是因为它没有使用:=
或评估LHS。 - yusuzech