1

假设我有一个情节列表,plotlist我想调用patchwork::wrap_plots(plotlist).

我还想在列表的开头再添加一个情节。

让我们从一个包含 2 个图的列表开始:

library(ggplot2)
library(patchwork)

cols <- c("mpg", "hp")

plot_col <- function(this_col) {
  ggplot(mtcars) +
    aes_string("wt", this_col) +
    geom_point()
}

plotlist <- lapply(cols, plot_col)

这有效:

res <- wrap_plots(plotlist)

但是等等,我还有一个情节。

p <- plot_col("qsec")

我可以在新情节之前p添加plotlist吗?

这些方法都不起作用:c(), list(),purrr::prepend()

newlist <- c(p, plotlist)
res <- wrap_plots(newlist)
#> Error: Only know how to add ggplots and/or grobs
newlist <- list(p, plotlist)
res <- wrap_plots(newlist)
#> Error: Only know how to add ggplots and/or grobs
newlist <- purrr::prepend(plotlist, p)
res <- wrap_plots(newlist)
#> Error: Only know how to add ggplots and/or grobs
4

1 回答 1

1
  1. 使用c()带有两个列表的函数(感谢Axeman):
newlist <- c(list(p), plotlist)
res <- wrap_plots(newlist)
  1. 使用rlist包提供的众多函数之一来操作列表:
# install.packages("rlist")
newlist <- rlist::list.prepend(plotlist, p)
res <- wrap_plots(newlist)
  1. 或者使用 for 循环构建一个新列表:
newlist <- list()
newlist[[1]] <- p
for (i in seq_along(plotlist)) {
  newlist[[i + 1]] <- plotlist[[i]]
}
res <- wrap_plots(newlist)
于 2020-01-07T19:31:49.820 回答