using geom_text_repel to customize labels where displaying at the end of lines

2.1k views Asked by At

In the plot below, I was wondering to know how can I customize the labels (state names) to reduce the gap between the labels? Here is part of my code that I believe needs to be modified.

ggrepel::geom_text_repel(aes(x =Year+1.6, y = Age.Adjusted.Rate, colour = State, label = State, fontface = 'bold'), data = d_filtered_top5_fe %>%
                         
                         filter(Year == max(Year)),
                       segment.color = 'transparent',
                       direction         = "y",
                       size = 2.5)+

enter image description here

1

There are 1 answers

2
tamtam On

Try setting the box.padding in geom_text_repel lower. The default is .25.

In a second step you can reduce space between overlapping text labels with the force argument.

df <- data.frame(y = rnorm(mean = 1, sd = .2, n = 50),
                 name = rep(LETTERS[1:10], each = 5),
                 x = rep(1:5, 10))


df %>% 
  ggplot(aes(x = x, y = y, color = name)) +
  geom_line() +
  ggrepel::geom_text_repel(aes(x = x + .1, 
                               y = y, 
                               colour = name, 
                               label = name, 
                               fontface = 'bold'), 
                           data = df %>%
                           filter(x == max(x)),
                           segment.color = 'transparent',
                           direction         = "y",
                           size = 2.5,
                           box.padding = .1,
                           force = .8) +
  scale_y_continuous(limits = c(0,2)) +
  theme_classic() +
  theme(legend.position = "none")