Search code examples
rggplot2venn-diagram

Create a Venn Diagram in R to represent rows with the same value from a dataframe


I want to create a Venn Diagram in R that represent the interesection between three columns of a dataframe, i.e. that represent how many observations are "1" for each pairwise comparison and also between the three groups.

Here is a reproducible example.

library(ggVennDiagram)
df <- as.data.frame(cbind(A=c(1,0,0,0,0,1,1,1,0,1),
                    B=c(0,0,1,1,0,0,0,1,1,0),
                    C=c(0,0,1,1,1,1,0,1,0,0)))

The resulting toy dataframe:

df
   A B C
1  1 0 0
2  0 0 0
3  0 1 1
4  0 1 1
5  0 0 1
6  1 0 1
7  1 0 0
8  1 1 1
9  0 1 0
10 1 0 0

So, I want to produce a Venn Diagram of the intesection of A, B and C, i.e. representing how many rows have "1" in common between A and B, B and C, A and C, and A B and C at the same time.

However, if I run ggVennDiagram(df) it does produce this plot: enter image description here

Which is obviously not the output that I am expecting. Anyone knows how can I solve?


Solution

  • You need a named list of integer vectors, which is equivalent to which(x == 1) for each column in your data frame, so you can do:

    ggVennDiagram(lapply(df, function(x) which(x == 1)))
    

    enter image description here