[英]pass string to facet_grid : 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')
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')
使用rlang
magic和新的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
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批准( 請參見此處的有趣討論 ),但對我來說很好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.