首页 > 解决方案 > 如何将参数列表传递给 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().

标签: rggplot2facet-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'))

推荐阅读