如何将参数列表传递给facet_grid()

时间:2018-06-20 16:22:30

标签: r ggplot2 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()

1 个答案:

答案 0 :(得分:0)

您只是忘记命名第二个参数,所以您将其传递给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'))
相关问题