Search code examples
rggplot2ggrepel

How to repel labels in ggplot


If the labels in the example below were to be overlapping, how could we implement a repel option? Thanks!

means <- df %>% 
  group_by(cyl) %>% 
  summarize(across(c(wt, mpg), mean))
ggplot(df)  +
  aes(x=wt, y=mpg, color=cyl, shape=cyl) + 
  geom_point() + 
  geom_point(size=4, data=means) + 
  geom_label(aes(label=cyl), color="black", data=means) -> fig
fig

If I add the geom_label_repel() from the ggrepel package

 fig + geom_label_repel()

I get the error:

geom_label_repel requires the gollowing missing aesthetics: label

Solution

  • You need to map label so that geom_label_repel "sees" it. It doesn't have direct view of the mapping from other geoms. Just itself and the top ggplot call. You thus have two options.

    Directly within the function

    geom_label_repel(mapping = aes(label = cyl))
    

    or in the top ggplot call

    ggplot(data = df, mapping = aes(label = cyl)) +
    

    Note that you'll probably have to specify data as Vincent mentioned in the comment if you want to label the means points.