R - 在同一图像中合并几个 (15) ggplot 对象

R - Merge several (15) ggplot objects in the same image

我只想在一张图像中合并 15 个 ggplot 对象。所有图在 x 和 y 上具有相同的维度。 例如,有 2 个对象:

 library(ggplot2)     

 a <- c(1:10)
 b <- c(5,4,3,2,1,6,7,8,9,10)

 a2 <- c(1:10)
 b2 <- c(10:1)

 df1 <- as.data.frame(x=a,y=b)
 df2 <- as.data.frame(x=a2,y=b2)

 p1 <- ggplot(df1,aes(a, b)) + geom_line()
 p2 <- ggplot(df2,aes(a2, b2)) + geom_point()

我尝试使用 plot_grid 但结果是 ggplot 对象的一张图像:

 library(cowplot)
 plot_grid(p1, p2, labels = "AUTO")

我也用网格,但和上面的结果一样。

我的临时解决方案是这样的:

 merge <- p1 +geom_point(data=df2,aes(x=a2, y=b2))

但是我有 15 个 ggplot 对象。有什么方法可以制作类似的东西吗?

 merge <- p1 + p2 +p3 ...+p15
 merge

请看图片,感谢您的帮助。

我们可以使用

library(ggplot2)
ggplot() + 
      geom_line(data = df1, aes(a, b)) + 
      geom_point(data = df2, aes(a2, b2))

-输出


或者如果我们已经创建了对象,reduce它并绘制

library(purrr)
p0 <- ggplot()
p1 <- geom_line(data = df1, aes(a, b))
p2 <-    geom_point(data = df2, aes(a2, b2))
mget(paste0('p', 0:2)) %>%
          reduce(`+`)