【问题标题】:Prepend a ggplot2 object to a list of plots [duplicate]将 ggplot2 对象添加到绘图列表中[重复]
【发布时间】:2020-01-07 19:31:49
【问题描述】:

假设我有一个地块列表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

【问题讨论】:

  • 您需要newlist &lt;- c(list(p), plotlist) 在正确的级别添加p
  • 在这种情况下你可能会这样做p + plotlist

标签: r ggplot2 patchwork


【解决方案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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-04
    • 2016-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-02
    • 1970-01-01
    相关资源
    最近更新 更多