将字符串传递给函数中的ggplot2

Tyl*_*ker 21 string r ggplot2

经常在工作中使用ggplot2并构建包装函数以加快我的工作流程.使用非标准评估(NSE)aes迫使我使用实际的变量名而不是传递字符串.所以我复制并重命名数据帧和变量名以安抚ggplot2.必须有一个更好的方法.如何通过函数包装器使ggplot2接受未知的数据帧和列名,而无需复制数据帧和使用通用列名?

这有效:

ggplot(mtcars, aes(x=mpg, y=hp)) +
    geom_point()
Run Code Online (Sandbox Code Playgroud)

这不是:

FUN <- function(dat, x, y) {
    ggplot(dat, aes(x = x, y = y)) +
        geom_point()
}

FUN(mtcars, "mpg", "hp")
Run Code Online (Sandbox Code Playgroud)

Tyl*_*ker 39

有一个aes_string功能,我没有真正看到突出,这正是这样做:

FUN <- function(dat, x, y) {
    ggplot(dat, aes_string(x = x, y = y)) +
        geom_point()
}

FUN(mtcars, "mpg", "hp")
Run Code Online (Sandbox Code Playgroud)

  • `aes_string` 已被软弃用。有关最新答案,请参阅 /sf/answers/3859373661/。 (4认同)

Ron*_*hah 19

现在建议使用.data代词

FUN <- function(dat, x, y) {
  ggplot(dat, aes(x = .data[[x]], y = .data[[y]])) +
    geom_point()
}

FUN(mtcars, "mpg", "hp")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

其他几个选择 -

#Using get
FUN <- function(dat, x, y) {
  ggplot(dat, aes(x = get(x), y = get(y))) +
    geom_point()
}

#Using sym

FUN <- function(dat, x, y) {
  ggplot(dat, aes(x = !!sym(x), y = !!sym(y))) +
    geom_point()
}
Run Code Online (Sandbox Code Playgroud)