Search code examples
rplotggplot2venn-diagram

R: print multiple types of plots on one page


I am trying to plot multiple plots in one page. I know functions like gridExtra::grid.arrange that can plot graphs generated by ggplot2 package. The problem I am facing is that I have two plots (bar.plot and density.plot below) that are generated by ggplot2 package and one plot generated using limma::vennDiagram function. I have tried the below but it is not working:

output <- paste('summary.pdf')
pdf(output,width = 25,height = 20)
par(mfrow = c(3, 3))
plot(bar.plot)
plot(density.plot)
print(vennDiagram(dat.venn, circle.col = col,cex = c(3,3,3)))
invisible(dev.off())

dat.venn is a data of type VennCounts:

 I-H-10003-T1-D1 I-H-10003-T2-D1 I-H-10003-T3-D1 Counts
               0               0               0      0
               0               0               1     41
               0               1               0     81
               0               1               1     66
               1               0               0     10
               1               0               1      2
               1               1               0      4
               1               1               1     56
attr(,"class")
[1] "VennCounts"

I am unable to find a venn diagram package that is compatible with the grid.arrange function. I don't think that VennCounts cant be printed out with grid.arrange function and ggplot2 plots can be printed out with par function.

UPDATE: I tried using pushViewport but it is still printing the venn diagram on the next page:

pdf(output,width = 25,height = 20)

# Create layout : nrow = 2, ncol = 2
pushViewport(viewport(layout = grid.layout(2, 2)))

# A helper function to define a region on the layout
define_region <- function(row, col){
  viewport(layout.pos.row = row, layout.pos.col = col)
} 

# Arrange the plots
print(bar.plot, vp = define_region(1, 1:2))
print(density.plot, vp = define_region(2, 1))
print(vennDiagram(dat.venn, circle.col = col,cex = c(3,3,3)), vp = define_region(2, 2))
dev.off()

Any help would be much appreciated!


Solution

  • First, save each of the files as .png files, such as save(yourfile, file = "yourname.png").

    Second, use the read.PNG function of the grid package to load them, such as yours.png <- readPNG("yourfile.PNG")

    After that, convert them with the rasterGrob function as in g1 <- rasterGrob(yours.png, interpolate=TRUE).

    Once all the plots are comparable in format, grid.arrange() does the trick. It might look like this:

    grid.arrange(g1, g2, g3, nrow=1)  # one row
    dev.copy(png,'threeplots.png')   # to save the array of plots     
    dev.off()                         # to close the device