将字符串传递给facet_grid:ggplot2

时间:2014-02-05 20:44:30

标签: r ggplot2

在ggplot2中,您可以使用aes_string在用户定义的函数内传递字符参数。对于采用公式而不是aes

的构面网格,您如何做同样的事情
FUN <- function(data, x, y, fac1, fac2) {
     ggplot(data = data, aes_string(x=x, y=y)) +
     geom_point() + facet_grid(as.formula(substitute(fac1 ~ fac2)))
}


FUN(mtcars, 'hp', 'mpg', 'cyl', 'am')

2 个答案:

答案 0 :(得分:30)

reformulate()似乎工作正常。

FUN <- function(data, x, y, fac1, fac2) {
      ggplot(data = data, aes_string(x=x, y=y)) +
      geom_point() + facet_grid(reformulate(fac2,fac1))
}

FUN(mtcars, 'hp', 'mpg', 'cyl', 'am')

enter image description here

答案 1 :(得分:3)

借助 rlang 魔术和新的 ggplot2 v3.0.0 功能,您可以执行以下操作:

FUN <- function(data, x, y, fac1, fac2) {
  ggplot(data = data, aes(x = !!ensym(x), y = !!ensym(y))) +
    geom_point() + 
    facet_grid(eval(expr(!!ensym(fac1) ~ !!ensym(fac2))))
}

FUN(mtcars, 'hp', 'mpg', 'cyl', 'am')

请注意,我们不使用已过时的aes_string

在这些情况下,我个人喜欢使用称为glue_formula的函数(引用程序包glue):

glue_formula <- function(.formula, .envir = parent.frame(), ...){
  formula_chr <- gsub("\\n\\s*","",as.character(.formula)[c(2,1,3)])
  args <- c(as.list(formula_chr), .sep=" ", .envir = .envir)
  as.formula(do.call(glue::glue, args),env = .envir)
}

FUN2 <- function(data, x, y, fac1, fac2) {
  ggplot(data = data, aes(x = !!ensym(x), y = !!ensym(y))) +
    geom_point() + facet_grid(glue_formula({fac1} ~ {fac2}))
}

FUN2(mtcars, 'hp', 'mpg', 'cyl', 'am')

它没有经过tidyverse批准(see interesting discussion here),但对我来说很好。