Search code examples
rvenn-diagram

Rounding values > 1000 to have "K" suffix R venn diagram


Here is my code:

library(VennDiagram)

# Generate 3 sets of 10000 words
set.seed(1)
set1 <- paste('word_',sample(c(1:100000) , 10000))
set.seed(2)
set2 <- paste('word_',sample(c(1:100000) , 10000))
set.seed(3)
set3 <- paste('word_',sample(c(1:100000) , 10000))

# Chart
p <- venn.diagram(
  x = list(set1, set2, set3),
  category.names = c("Set 1" , "Set 2 " , "Set 3"),
  filename = NULL
)

grid.newpage()
grid.draw(p)
dev.off()

In the labels for numbers I hope to round off values greater than 1000 to have the "K" prefix, eg 8043 -> 8K


Solution

  • There doesn't seem to be an option to achieve this within the function. However, since it returns a gList, we can reach into the result and modify the text labels in place:

    p <- venn.diagram(
      x = list(set1, set2, set3),
      category.names = c("Set 1" , "Set 2 " , "Set 3")
    )
    
    p <- do.call(grid::gList, lapply(p, function(x) {
      if(is.null(x$label)) return(x)
      if(is.na(suppressWarnings(as.numeric(x$label)))) return(x)
      val <- as.numeric(x$label)
      if(val < 1000) return(x)
      x$label <- paste0(floor(val / 1000), "K")
      x
    }))
    
    grid.newpage()
    grid.draw(p)
    

    enter image description here

    Created on 2022-09-18 with reprex v2.0.2