Search code examples
rggplot2plotmergeggplotly

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


I want to merge 15 ggplot objects in only one image. All Plots has the same dimensions on x and y. For example, with 2 objects:

 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()

I tried with plot_grid but the result is one image for ggplot object:

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

Me too with grids but is the same result of above.

My temporal solution is this:

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

But I have 15 ggplot object. It is any way to make something like?

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

See the pictures please and thanks for your help.

I want this result Undesirable result


Solution

  • We could use

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

    -output

    enter image description here


    Or if we have already created the objects, reduce it and plot

    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(`+`)
    

    enter image description here