【问题标题】:How to pass a list of arguments to facet_grid()如何将参数列表传递给 facet_grid()
【发布时间】:2018-11-29 20:45:20
【问题描述】:

我正在尝试将参数列表传递给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()

【问题讨论】:

    标签: r ggplot2 facet-grid


    【解决方案1】:

    您只是忘记命名第二个参数,因此将其传递给 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.args 列表中专门命名它,以便我可以传递任意数量的命名参数(例如facet.args = list('Species', scales = 'free_x', space = 'free_x'))。
    • 你需要使用do.call。函数中的第一个修改列表的第一个元素以合并 ~。然后使用... + do.call(facet.grid, facet.args)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-13
    • 2013-11-06
    • 2019-12-10
    • 1970-01-01
    相关资源
    最近更新 更多