rstringggplot2venn-diagram

VennDiagram: How to show label = item (not count), and exclude character(0), 0 (0%), and related strings?


# # reproducible example

library(ggVennDiagram)

set.seed(0)
small_list <- lapply(sample(0:10, size = 4), function(x){
  sample(letters,x)
})
                
names(small_list) <- c("Mercury", "Venus", "Earth", "Mars")

# via ggVennDiagram
# how to remove "0 (0%)" from intersections without an element?

ggVennDiagram(small_list, label_alpha = 0)

ggVennDiagram(small_list, 
                    category.names = LETTERS[1:4], 
                    show_intersect = TRUE)                  

# via ggplot
# how to remove the "c(", ")", and quotation marks from each item label?
# how to remove "character(0)" from intersections without an element?

venn <- Venn(small_list)
data <- process_data(venn)
View(data)

ggplot() +
  # 1. region count layer
  geom_sf(aes(fill = count), data = venn_region(data)) +
  # 2. set edge layer
  geom_sf(aes(color = id), data = venn_setedge(data), show.legend = FALSE) +
  # 3. set label layer
  geom_sf_text(aes(label = name), data = venn_setlabel(data)) +
  # 4. region label layer
  # geom_sf_label(aes(label = count), data = venn_region(data)) +
  geom_sf_label(aes(label = item), data=venn_region(data)) +
  theme_void()

Solution

  • Though I may not fully understand what kind of labels you desire to plot I hope this idea might help: use data argument processing inside labelling function:

    ggplot() +
      # 1. region count layer
      geom_sf(aes(fill = count), data = venn_region(data)) +
      # 2. set edge layer
      geom_sf(aes(color = id), data = venn_setedge(data), show.legend = FALSE) +
      # 3. set label layer
      geom_sf_text(aes(label = name), data = venn_setlabel(data)) +
      # 4. region label layer
      # geom_sf_label(aes(label = count), data = venn_region(data)) +
      geom_sf_label(aes(label = item, group = id), data=venn_region(data) %>% 
                      rowwise %>% 
                      mutate(item = ifelse(identical(item, character(0)),
                                           NA,
                                           item %>% unlist() %>% paste(collapse = ", ")))) +
      theme_void()
    

    So the character(0) values and c("", "") are removed. I pay your attention to the fact that items don't have values assigned to all regions: enter image description here