我想创建一个函数,生成一个
特别地,如果可能的话,我希望在
但是,我所做的所有尝试都失败了。
使用一个非
ggplot
绘图,并提供一个用于分面变量到 facet_grid()
的可选参数。特别地,如果可能的话,我希望在
facet_grid
中内嵌条件逻辑。我还想使用整洁评估框架 - 因此不使用公式字符串!但是,我所做的所有尝试都失败了。
library(tidyverse)
iris <- iris %>% add_column(idx = rep(1:2, 75))
我的第一次尝试失败了,因为 facet_grid
试图找到一个名为 NULL
(用反引号括起来)的变量。
plot_iris <- function(df_in, facet_var = NULL){
ggplot(df_in) +
geom_point(aes(Sepal.Length, Sepal.Width)) +
facet_grid(vars(!!enquo(facet_var)), vars(idx))
}
plot_iris(iris)
#> Error: At least one layer must contain all faceting variables: `NULL`.
#> * Plot is missing `NULL`
#> * Layer 1 is missing `NULL`
运行plot_iris(iris, Species)
没有问题。
我的第二次尝试也失败了,但是错误信息不同。
plot_iris2 <- function(df_in, facet_var = NULL){
facet_quo <- enquo(facet_var)
ggplot(df_in) +
geom_point(aes(Sepal.Length, Sepal.Width)) +
facet_grid(rows = ifelse(identical(facet_quo, quo(NULL)), NULL,
vars(!!facet_quo)),
cols = vars(idx))
}
plot_iris2(iris)
#> Error in ans[test & ok] <- rep(yes, length.out = length(ans))[test & ok] :
#> replacement has length zero
#> In addition: Warning message:
#> In rep(yes, length.out = length(ans)) :
运行这个尝试时,非NULL
可选参数也会失败:
plot_iris2(iris, Species)
#> Error: `rows` must be `NULL` or a `vars()` list if `cols` is a `vars()` list
我的第三次尝试也失败了,出现了相同的错误信息,但是警告不同:
plot_iris3 <- function(df_in, facet_var = NULL){
facet_quo <- enquo(facet_var)
ggplot(df_in) +
geom_point(aes(Sepal.Length, Sepal.Width)) +
facet_grid(rows = vars(ifelse(identical(facet_quo, quo(NULL)), NULL,
!!facet_quo)))
}
plot_iris3(iris)
#> Error in ans[test & ok] <- rep(yes, length.out = length(ans))[test & ok] :
#> replacement has length zero
#> In addition: Warning message:
#> In rep(yes, length.out = length(ans)) :
#> 'x' is NULL so the result will be NULL
使用一个非
NULL
的可选参数返回一个按idx
分面绘制的图表,但不会按Species
分面 - 单行有一个分面标签,标记为“1”。plot_iris3(iris, Species)
有没有其他替代方案,在单个facet_grid
调用内使用条件逻辑,并且在可选参数为NULL
时也能正常工作?
facet_grid(vars() vars())
会失败?谢谢! - Matifou