Search code examples
rggplot2venn-diagram

Venn Diagram in R to show character labels


I'm very new to R and trying to create a 4-dimensional Venn diagram with a data which contains all categorical variables. For instance, if i have the data below and I want to create a Venn Diagram in R to show the word "hello" at the intersection of A & B instead of the counts and percentages, how do i do that? I used the code ggVennDigram(x) after creating the list below and it gave me the counts instead of the actual data labels.

x=list()                        
x$A=as.character(c("hello"))
x$B=as.character(c("hello", "how", "are"))
x$C=as.character(c("how", "You"))
x$D=as.character(c("me", "her", "they"))

Solution

  • The graph cannot be label by default. This is solution with some hack. (modified from Venn Diagram with Item labels)

    library(VennDiagram)
    library(stringr)
    library(purrr)
    
    # Generate plot
    v <- venn.diagram(x,
                      fill = c("orange", "blue", "red", "green"),
                      filename=NULL)
    
    # Calculate overlap site
    overlaps <- calculate.overlap(x)
    overlaps <- overlaps[str_sort(names(overlaps), numeric = TRUE)] # sort base on numeric value
    
    # Apply name to global variable
    # Index of venn diagram start at calculate.overlaps + 8. You have to find the index value by yourself for (3,5,6,7,.. venn)
    walk2(seq(overlaps) +8, seq(overlaps),  
          function(x,y) {v[[x]]$label <<- paste0(overlaps[[y]], collapse = "\n")})
    
    # Draw plot
    grid.draw(v)
    

    enter image description here