r-使用带有列表和额外参数的网格排列



这是一个与此相同的问题:如何使用grid.array排列变量列表?,但有额外的参数,例如图例。

这是一个玩具的例子。

数据如下:

Country = c("France", "Italy", "Peru", "Canada", "Brazill", "Spain", "Macedonia", "Austria")
Diet = c("carnivore", "homnivore", "vegtarian", "vegan")
n = 1000
data1 = data.frame("Country" = sample(Country, n, replace = TRUE),
"Diet" = sample(Diet, n, replace = TRUE),
"X" = sample(c(1 : 20), n, replace = TRUE),
"Y" = sample(rnorm(n))) 

以下是一个制作传奇的中间情节:

plot = ggplot(data1, aes(x = Diet, fill = Diet)) + geom_histogram(stat = "count") + theme(legend.position = "bottom")
plot
legend <- cowplot::get_legend(plot)

这是我将与网格一起排列的地块列表。排列:

Countries = data1$Country %>% unique
n = length(Countries)
l = lapply(c(1 : n), function(x) ggplot(data1 %>% filter(Country == Countries[[x]]), aes(x = Diet, fill = Diet)) + geom_histogram(stat = "count"))

这是我想要的结果:

grid.arrange(legend, l[[2]], l[[3]], ncol = 2, layout_matrix = rbind(c(2, 3), c(1, 1)))

以下是我想写它的方式(不写l[[1]],l[[2]];如果我有很多情节,这很有用(

do.call("grid.arrange", c(legend, l[1 : 2], ncol = 2, layout_matrix = rbind(c(2, 3), c(1, 1))))

但它不起作用

然而,它在没有额外参数的情况下工作:

do.call("grid.arrange", c(l[1 : 2], ncol = 2))

您的问题是如何组合列表。你正在这样做:

a <- list(1, 2)
b <- list(list(3, 4), list(5, 6))
c <- 7
c(a, b, c)

结果,所有内容都被添加到a列表中。

你想要的是:

c(list(a), b, c)

最新更新