How to draw Venn diagram using R

Jack picture Jack · Oct 19, 2013 · Viewed 16.4k times · Source

I have three lists of IDs.

I would like to compare the 3 lists,and draw a Venn diagram. In the Venn diagram obtained I would show in the intersection not numbers but ID's. I need to do that in R, but I really do not know how. Could you help me? That`s my code. It works, but show just numbers, I would show "terms" into intersections

       set1 <- unique(goterm1)
       set2 <- unique(goterm2)
        set3 <- unique(goterm3)

       require(limma)
       Diagram <- function(set1, set2, set3, names)
       {
     stopifnot( length(names) == 3)
      # Form universe as union of all three sets
      universe <- sort( unique( c(set1, set2, set3) ) )
      Counts <- matrix(0, nrow=length(universe), ncol=3)
      colnames(Counts) <- names
        for (i in 1:length(universe))
        {
        Counts[i,1] <- universe[i] %in% set1
        Counts[i,2] <- universe[i] %in% set2
       Counts[i,3] <- universe[i] %in% set3
       }

         vennDiagram( vennCounts(Counts) )}

       Diagram(set1, set2, set3, c("ORG1", "ORG2", "ORG3"))
        Venn

Answer

user2357031 picture user2357031 · Oct 19, 2013

You can accomplish the feat with limma, also. See the example below.

The idea is basically exactly the same as in the code you have posted, but it has not been wrapped into a function (and is therefore possibly slightly easier to debug).

Do you get it to work with the code below? If not, please post the possible error messages and warnings that you get.

# Load the library
library(limma)

# Generate example data
set1<-letters[1:5]
set2<-letters[4:8]
set3<-letters[5:9]

# What are the possible letters in the universe?
universe <- sort(unique(c(set1, set2, set3)))

# Generate a matrix, with the sets in columns and possible letters on rows
Counts <- matrix(0, nrow=length(universe), ncol=3)
# Populate the said matrix
for (i in 1:length(universe)) {
   Counts[i,1] <- universe[i] %in% set1
   Counts[i,2] <- universe[i] %in% set2
   Counts[i,3] <- universe[i] %in% set3
}

# Name the columns with the sample names
colnames(Counts) <- c("set1","set2","set3")

# Specify the colors for the sets
cols<-c("Red", "Green", "Blue")
vennDiagram(vennCounts(Counts), circle.col=cols)

The code should give a plot similar to:

enter image description here