r - 如何将参数列表传递给 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'))
推荐阅读
- c# - 用范围内的值填充列表
- python - 熊猫分组日期和时间总和
- node.js - Node.js mssql 模块事务不适用于异步等待
- c# - 如何修复此 webapi 路由配置?
- html - ngModel 的副本也会受到影响
- python - 计算列表中重复元组的数量
- android - Ionic Cordova Build Android 期间面临错误
- c# - 我们可以使用 C# 以编程方式将 DLL 文件添加到特定文件夹中吗
- laravel - Laravel 站点错误地重定向到 site.com/public/public
- c# - Excel 2016 到 Windows 窗体 Visual Studio 2019 社区中的 DataGridView