我想创建一个产生 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
时,该方法有效?
最佳答案
也许我们应该删除 NULL
vars 规范中的元素使这更容易。我打开了一个问题:https://github.com/tidyverse/ggplot2/issues/2986
您可以使用 rlang::quo_is_null()
检查 quo(NULL)
.为了清楚起见,我会在一个单独的步骤中进行。
plot_iris <- function(df_in, facet_var = NULL){
facet_quo <- enquo(facet_var)
if (rlang::quo_is_null(facet_quo)) {
rows <- vars()
} else {
rows <- vars(!!facet_quo)
}
ggplot(df_in) +
geom_point(aes(Sepal.Length, Sepal.Width)) +
facet_grid(rows, vars(idx))
}
关于r - ggplot2 具有条件面和整洁评估的面网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53218152/