0

I'm trying to assign labels to points in ggplot based on a certain criteria (value > 0.4), but I want the colour of the points to apply based on the team name. I can do colour and labels for ALL data points (which looks really messy), but struggling to apply the label criteria.

Have tried copying this example, but it doesn't allow for colouring the points by team:

Label points in geom_point

Plot <- ggplot(data = df, aes(x=Prem$Expected.Goals.p90..exl.pens., y=Prem$Expected.Assists.p90, color=Prem$Team, label=Prem$Player)) + 
geom_point() +
geom_abline(intercept = 0, linetype = 2, colour = "darkblue") + 
scale_x_continuous(name = "Non-penalty Expected Goals per 90", limits = c(0, 0.7)) +
scale_y_continuous(name = "Expected Assists per 90", limits = c(0, 0.7)) + 
theme_bw() +
scale_colour_manual(values = c("firebrick1", "green", "navy", "darksalmon", "brown4", "darkgreen", "dodgerblue", "yellow", "orange", "blue", "black", "lightblue")) 


Plot + geom_label_repel(aes(label = (Prem$Player)),

              box.padding   = 0.35, 
              point.padding = 0.5,
              segment.color = 'grey50')


df1 <- subset(df, Prem$Expected.Goals.p90..exl.pens. > 0.4)

Plot + geom_label_repel(data = df1,    aes(x=df1$Expected.Goals.p90..exl.pens., y=df1$Expected.Assists.p90, label=df1$Player),
size = 5,
box.padding = unit(0.35, "lines"),
point.padding = unit(0.3, "lines")

)

Have tried to create a subset df1 to deal with this, but I'm getting the following error message:

Error: Aesthetics must be either length 1 or the same as the data (8): x, y, label, colour

enter image description here

enter image description here

M--
  • 25,431
  • 8
  • 61
  • 93

1 Answers1

0

From the help page of geom_text_repel, you can omit labels by adding "" instead of text to a labelling column:

p <- ggplot(mtcars, aes(wt, mpg, label = rownames(mtcars), colour = factor(cyl))) +
geom_point()

mtcars$label <- rownames(mtcars)
mtcars$label[1:15] <- ""
p + geom_text_repel(data = mtcars, aes(wt, mpg, label = label))

It's a bit hard to imagine exactly what to do without reproducible data, but in your case, I think all you have to do is create a label column and add "" to the lines in which your Expected.Goals.p90..exl.pens. column is above 0.4:

Prem$label <- Prem$Player
Prem[Prem$Expected.Goals.p90..exl.pens. > 0.4, "label"] <- ""

# ... Create 'Plot' object, and add:

Plot + geom_label_repel(aes(label = label))
pedrostrusso
  • 388
  • 3
  • 10