gpt4 book ai didi

r - 如何使用 grid.arrange 排列任意数量的 ggplot?

转载 作者:行者123 更新时间:2023-12-03 04:56:56 27 4
gpt4 key购买 nike

这是在 ggplot2 google 群组上交叉发布的

我的情况是我是working on a function输出任意数量的图(取决于用户提供的输入数据)。该函数返回 n 个图的列表,我想将这些图以 2 x 2 的形式排列。我正在努力解决以下同时发生的问题:

  1. 如何才能灵活地处理任意 (n) 个绘图?
  2. 我怎样才能指定我希望它们布置为 2 x 2

我当前的策略使用 gridExtra 包中的 grid.arrange。它可能不是最佳的,特别是因为,这是关键,它完全不起作用。这是我的注释示例代码,尝试了三个图:

library(ggplot2)
library(gridExtra)

x <- qplot(mpg, disp, data = mtcars)
y <- qplot(hp, wt, data = mtcars)
z <- qplot(qsec, wt, data = mtcars)

# A normal, plain-jane call to grid.arrange is fine for displaying all my plots
grid.arrange(x, y, z)

# But, for my purposes, I need a 2 x 2 layout. So the command below works acceptably.
grid.arrange(x, y, z, nrow = 2, ncol = 2)

# The problem is that the function I'm developing outputs a LIST of an arbitrary
# number plots, and I'd like to be able to plot every plot in the list on a 2 x 2
# laid-out page. I can at least plot a list of plots by constructing a do.call()
# expression, below. (Note: it totally even surprises me that this do.call expression
# DOES work. I'm astounded.)
plot.list <- list(x, y, z)
do.call(grid.arrange, plot.list)

# But now I need 2 x 2 pages. No problem, right? Since do.call() is taking a list of
# arguments, I'll just add my grid.layout arguments to the list. Since grid.arrange is
# supposed to pass layout arguments along to grid.layout anyway, this should work.
args.list <- c(plot.list, "nrow = 2", "ncol = 2")

# Except that the line below is going to fail, producing an "input must be grobs!"
# error
do.call(grid.arrange, args.list)

正如我习惯做的那样,我谦卑地蜷缩在角落里,热切地等待比我聪明得多的社区的明智反馈。特别是如果我让这件事变得比需要的更加困难。

最佳答案

你就快到了!问题是 do.call 期望您的参数位于命名的 list 对象中。您已将它们放入列表中,但作为字符串,而不是命名列表项。

我认为这应该有效:

args.list <- c(plot.list, 2,2)
names(args.list) <- c("x", "y", "z", "nrow", "ncol")

正如 Ben 和 Joshua 在评论中指出的那样,我可以在创建列表时指定名称:

args.list <- c(plot.list,list(nrow=2,ncol=2))

args.list <- list(x=x, y=y, z=x, nrow=2, ncol=2)

关于r - 如何使用 grid.arrange 排列任意数量的 ggplot?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6681145/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com