Skip to content

How to extract labels shown by ggrepel #254

@jttoivon

Description

@jttoivon

Hi,

How can I extract a list of those labels that ggrepel shows in the result figure?
In the below example I create 500 points, and ggrepel shows label for 395 of these points only. However, when I
try to extract the list of these 395 labels, I get all 500 labels. Any idea what I am doing wrong?

library(tidyverse)
library(ggrepel)
library(grid)
dev.size()
create_data <- function(n=10) {
  x <- runif(n)
  y <- runif(n)
  label <- paste0("***",1:n,"***")
  df <- tibble(x=x, y=y, label=label)
  df
}
set.seed(123)
tmp <- create_data(n=500)
g <- tmp %>% ggplot(aes(x, y, label=label)) + geom_text_repel()
g
extract_labels <- function(g, width=9.8, height=7) {
  # Trying to imitate solution to this https://github.com/slowkow/ggrepel/issues/24
  grid.newpage()
  pushViewport(viewport(width = width, height = height))
  gg <- g %>% ggplotGrob() %>% grid.force()
  print(gg)
  xx <- gg %>% getGrob("textrepeltree", grep = TRUE)
  xx
}
res <- extract_labels(g)
n_distinct(res$data$label)   # all 500 are here
length(res$children)         # this is also 500

Here is an image of the output produced by the code:

image

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions