Is there a way to use geom_label_repel when a full dataset is passed to ggplot?

82 views Asked by At

Is there a way to use geom_label_repel when a full dataset is passed to ggplot?

I can use geom_label_repel() in the following example by including mtcars only within geom_point()

library(tidyverse)
library(ggrepel)

ggplot() +
    geom_point(
        data = mtcars, 
        aes(x = wt, y = mpg)) +
    geom_label_repel(
        aes(x = 2.5, y = 23.92395),
        color = "red", label = "My car prediction"
    ) 

If I include mtcars within ggplot(), then geom_label_repel() gets "overwhelmed" with overlaps.

ggplot(data = mtcars) +
    geom_point( 
        aes(x = wt, y = mpg)) +
    geom_label_repel(
        aes(x = 2.5, y = 23.92395),
        color = "red", label = "My car prediction"
    ) 

Is there someway to pass data into ggplot(data = mtcars) and still use geom_label_repel()?

ggplot(data = mtcars) +
    geom_point( 
        aes(x = wt, y = mpg)) +
    geom_label_repel(
        data = NULL, # this doesn't work but is there something like it? 
        aes(x = 2.5, y = 23.92395),
        color = "red", label = "My car prediction"
    ) 
1

There are 1 answers

2
asd-tm On BEST ANSWER

You can filter out your data:

ggplot(data = mtcars) +
  geom_point( 
    aes(x = wt, y = mpg)) +
  geom_label_repel(
    aes(x = 2.5, y = 23.92395), data = \(x) filter(x, F),
    color = "red", label = "My car prediction"# , max.overlaps = 100 
  ) 

enter image description here