在r的一页上显示ggplot的多个图

zes*_*sla 5 for-loop r ggplot2

我想在一个循环中制作多个ggplot,并在一个绘图上显示它们。

for ( i in 1:8) {
    g <- ggplot(data=mtcars, aes(x=hp, y=wt))+
        geom_point()
    print(g)
}
Run Code Online (Sandbox Code Playgroud)

我想将上面的图安排在一页,四行和两列上。有谁知道这是怎么做到的吗?谢谢。

Tun*_*ung 7

您可以将所有绘图保存在一个list然后使用cowplot::plot_grid()gridExtra::marrangeGrob()将它们放在一个或多个页面中

也可以看看:

library(tidyverse)

# create a list with a specific length 
plot_lst <- vector("list", length = 8)

for (i in 1:8) {
  g <- ggplot(data = mtcars, aes(x = hp, y = wt)) +
    geom_point()
  plot_lst[[i]] <- g
}

# Combine all plots
cowplot::plot_grid(plotlist = plot_lst, nrow = 4)
Run Code Online (Sandbox Code Playgroud)

library(gridExtra)
ml1 <- marrangeGrob(plot_lst, nrow = 2, ncol = 2)
ml1
Run Code Online (Sandbox Code Playgroud)

reprex 包(v0.2.1.9000)于 2018 年 9 月 20 日创建