Home > Net >  Use geom_label_repel only for certain observations?
Use geom_label_repel only for certain observations?

Time:05-30

I'm a football data analyst using NFL team logos as my points on a scatterplot. However, these images will sometimes cover each other up. I want to find a way to repel a label for those images that are overlapping with one another. However, I only want to have a repelled label for points where the team image is not fully visible. Is there a way to have R only insert labels for a few datapoints? I've attached an image below in which all datapoints have a label attached. My current call to geom_label_repel is:

ggplot geom_label_repel(label.size = 0.1)

Any advice is greatly appreciated!

Current ggplot

CodePudding user response:

You could do something like this to choose the labels you want:

library(tidyverse)
library(ggrepel)

df <- tribble(~team, ~aay, ~epa,
        "LA", 8, 5,
        "PIT", 6, -2,
        "KC", 7, 5,
        "DAL", 7, 5
        )

# Select desired labels
labels <- df |> filter(team %in% c("KC", "DAL"))

df |> 
  ggplot(aes(aay, epa))  
  geom_point()  
  geom_label_repel(aes(label = team), data = labels, force = 20)  
  xlim(c(0, 10))  
  ylim(c(-8, 8))

Created on 2022-05-25 by the reprex package (v2.0.1)

  • Related