Search code examples
rr-gridvenn-diagramcowplotgrob

R graphics: How to make objects from VennDiagram compatible with cowplot plot_grid?


I am making Venn diagrams with the VennDiagram package. They are coming out OK:

library(VennDiagram)
library(cowplot)


png("p.png")
p = draw.pairwise.venn(30,20,11, category = c("Dogs", "Cats"), lty = rep("blank", 2), fill = c("light blue", "pink"), alpha = rep(0.5, 2), cat.pos = c(-45, 45), cat.dist = rep(0.025, 2))
dev.off()

png("q.png")
draw.pairwise.venn(15, 20, 10, category = c("Rats", "Mice"), lty = rep("blank", 2), fill = c("light blue", "pink"), alpha = rep(0.5, 2), cat.pos = c(-45, 45), cat.dist = rep(0.025, 2))
dev.off()    

enter image description here enter image description here

But if I try to plot them side by side using cowplot's plot_grid() bad things occur:

p = draw.pairwise.venn(30,20,11, category = c("Dogs", "Cats"), lty = rep("blank", 2), fill = c("light blue", "pink"), alpha = rep(0.5, 2), cat.pos = c(-45, 45), cat.dist = rep(0.025, 2))

q = draw.pairwise.venn(15, 20, 10, category = c("Rats", "Mice"), lty = rep("blank", 2), fill = c("light blue", "pink"), alpha = rep(0.5, 2), cat.pos = c(-45, 45), cat.dist = rep(0.025, 2))

png('pq.png')
plot_grid(p, q, labels = "AUTO")
dev.off()

Error: Argument needs to be of class "ggplot", "gtable", "grob", "recordedplot", or a function that plots to an R graphicsdevice when called, but is a gList
Calls: plot_grid -> align_plots -> lapply -> FUN -> plot_to_gtable
Execution halted

draw.pairwise.venn() is not making objects compatible with plot_grid().

class(p)
[1] "gList"

So I guess I need to make gList into ggplot object or something else compatible, even though gList is listed as a suitable type. I have not been able to find anything. I want to use cowplot due to its nice ability to label sub figures for publication.


Solution

  • Wrapping these plots into a grobTree() works for me. I think the VennDiagram package is to blame here. It shouldn't return a gList, it should wrap the gList into a grob. In any case, this can be fixed in cowplot. Feel free to file an issue here.

    library(VennDiagram)
    #> Loading required package: grid
    #> Loading required package: futile.logger
    library(cowplot)
    library(grid)
    
    p = draw.pairwise.venn(30,20,11, category = c("Dogs", "Cats"), lty = rep("blank", 2), fill = c("light blue", "pink"), alpha = rep(0.5, 2), cat.pos = c(-45, 45), cat.dist = rep(0.025, 2))
    
    q = draw.pairwise.venn(15, 20, 10, category = c("Rats", "Mice"), lty = rep("blank", 2), fill = c("light blue", "pink"), alpha = rep(0.5, 2), cat.pos = c(-45, 45), cat.dist = rep(0.025, 2))
    
    plot_grid(grobTree(p), grobTree(q), labels = "AUTO")
    

    Created on 2018-06-23 by the reprex package (v0.2.0).