如何将参数列表传递给 facet_grid()
How to pass a list of arguments to facet_grid()
我试图将参数列表传递给 facet_grid()
以赋予函数更大的灵活性,但 facet_grid()
似乎将列表中的所有内容都视为分面变量或其他东西。它没有返回错误,但也没有我预期的行为。这是我为实现此目的而尝试组合的代码:
facet_plot <- function(facet.args){
ggplot(iris, aes(x = Sepal.Length, y = Petal.Length)) +
geom_point() +
facet_grid(paste0('~', facet.args$facets), facet.args[which(names(facet.args) != 'facets')])
}
facet_plot(list(facets = 'Species', scales = 'free_x'))
我想要实现的是:
ggplot(iris, aes(x = Sepal.Length, y = Petal.Length)) +
geom_point() +
facet_grid(~Species, scales = 'free_x')
我希望能够将任意数量的附加参数传递给 facet_grid()
。
你只是忘了命名第二个参数,所以你将它传递给了 margin
而不是传递给了 scales
(并且你需要双括号才能使参数成为向量):
facet_plot <- function(facet.args){
ggplot(iris, aes(x = Sepal.Length, y = Petal.Length)) +
geom_point() +
facet_grid(paste0('~', facet.args$facets), scales= facet.args[[which(names(facet.args) != 'facets')]])
}
facet_plot(list(facets = 'Species', scales = 'free_x'))
为了更通用,您可以使用 do.call
:
facet_plot <- function(facet.args){
facet.args$facets <- paste0('~', facet.args$facets)
ggplot(iris, aes(x = Sepal.Length, y = Petal.Length)) +
geom_point() +
do.call(facet_grid,facet.args)
}
facet_plot(list(facets = 'Species', scales = 'free_x'))
我试图将参数列表传递给 facet_grid()
以赋予函数更大的灵活性,但 facet_grid()
似乎将列表中的所有内容都视为分面变量或其他东西。它没有返回错误,但也没有我预期的行为。这是我为实现此目的而尝试组合的代码:
facet_plot <- function(facet.args){
ggplot(iris, aes(x = Sepal.Length, y = Petal.Length)) +
geom_point() +
facet_grid(paste0('~', facet.args$facets), facet.args[which(names(facet.args) != 'facets')])
}
facet_plot(list(facets = 'Species', scales = 'free_x'))
我想要实现的是:
ggplot(iris, aes(x = Sepal.Length, y = Petal.Length)) +
geom_point() +
facet_grid(~Species, scales = 'free_x')
我希望能够将任意数量的附加参数传递给 facet_grid()
。
你只是忘了命名第二个参数,所以你将它传递给了 margin
而不是传递给了 scales
(并且你需要双括号才能使参数成为向量):
facet_plot <- function(facet.args){
ggplot(iris, aes(x = Sepal.Length, y = Petal.Length)) +
geom_point() +
facet_grid(paste0('~', facet.args$facets), scales= facet.args[[which(names(facet.args) != 'facets')]])
}
facet_plot(list(facets = 'Species', scales = 'free_x'))
为了更通用,您可以使用 do.call
:
facet_plot <- function(facet.args){
facet.args$facets <- paste0('~', facet.args$facets)
ggplot(iris, aes(x = Sepal.Length, y = Petal.Length)) +
geom_point() +
do.call(facet_grid,facet.args)
}
facet_plot(list(facets = 'Species', scales = 'free_x'))