【问题标题】:How to add several blank ggplots to the list?如何将几个空白 ggplots 添加到列表中?
【发布时间】:2021-07-02 08:39:42
【问题描述】:

假设我们想要绘制一些 ggplot 和三个空图。例如:

library(ggplot2)
lst <- list(ggplot() + aes(1:10, 1:10) + geom_line())
for (i in 1:3) {
  lst[[i+1]] <- ggplot() +
    theme_void()
}
patchwork::wrap_plots(lst)

正如你在我的代码中看到的,我分配给列表的人是

for (i in 1:3) {
  lst[[i+1]] <- ggplot() +
    theme_void()
}

我的问题是 - 是否有可能添加这三个图但没有循环?我尝试了一些 lpply,但它导致我一无所获

【问题讨论】:

    标签: r list loops ggplot2


    【解决方案1】:

    怎么样:

    plot1 <- ggplot() + aes(1:10, 1:10) + geom_line()
    lst <- c(list(plot1), rep(list(ggplot() + theme_void()), 2))
    

    【讨论】:

    • 它真的适合你吗?我得到:"Error: 'list' object cannot be coerced to type 'double'"
    • 应该是rep(ggplot() + theme_void(), 2)
    • 试试这个:lst &lt;- c(list(plot1), rep(list(ggplot() + theme_void()), 2))
    • 哇,好用。您可以将此添加为答案,以便我接受它
    • 我已根据@teunbrand 的评论更正了答案
    【解决方案2】:

    厚颜无耻的解决方案:

    library(ggplot2)
    library(patchwork)
    p <- ggplot() + aes(1:10, 1:10) + geom_line()
    
    wrap_plots(p, nrow = 2, ncol = 2)
    

    附注我个人更喜欢使用 plot_spacer() 而不是 theme_void。 Plots with theme_void can have weird behaviour...

    【讨论】:

      猜你喜欢
      • 2011-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多