在函数内部时,ggplot2的aes_string()不喜欢“ rownames(mtcars)”

max*_*eld 4 r ggplot2

我需要依靠来在函数内部生成图aes_string(),并且需要标签作为行名。

下面的图表可以正常工作,但不能在函数内部使用

library(ggplot2)
data(mtcars)
plotfun <- function(cars) {
  g <- ggplot(data = cars, aes_string(x = "mpg", y = "disp", label = "rownames(cars)"))
  g <- g + geom_point()
  g <- g + geom_text()
  g
}
plotfun(cars = mtcars)
Run Code Online (Sandbox Code Playgroud)

当作为函数运行时,这使我:

Error: Aesthetics must either be length one, or the same length as the dataProblems:mpg, disp
Run Code Online (Sandbox Code Playgroud)

我不能把头缠住它。我知道关于函数内部存在很多类似的问题aes_string() –我只是无法使其解决方案适应我的问题。

附言:显然,以上MWE很愚蠢;在我的实际用例中,我通过for循环运行该图,因此需要使用aes_string()

MrF*_*ick 5

我认为这里最好为您服务,aes_q而不是aes_string

library(ggplot2)
data(mtcars)
plotfun <- function(cars) {
  g <- ggplot(data = cars, aes_q(x = as.name("mpg"), y = as.name("disp"), label=rownames(cars)))
  g <- g + geom_point()
  g <- g + geom_text()
  g
}
plotfun(cars = mtcars)
Run Code Online (Sandbox Code Playgroud)

aes_q允许,所以我们只需要使用你传递未计算的符号,并呼吁as.name()到您的字符串转换成可以在你随后的数据进行评估符号。