0

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

Nader Mehri
  • 514
  • 1
  • 5
  • 21
  • This can be solved, can you please share `d_filtered_top5_fe` using `dput(d_filtered_top5_fe)` otherwise you will not get a proper answer for your issue! – Duck Oct 21 '20 at 15:01

1 Answers1

1

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")
                 

tamtam
  • 3,541
  • 1
  • 7
  • 21
  • Thanks for your answer. I applied your suggested solution and updated my question. Why Massachuset does not behave well? I think this happens because the state name is too long to fit in the plot. Is there any way to fix this? – Nader Mehri Oct 21 '20 at 19:57
  • This question continued at https://stackoverflow.com/questions/64471457/how-to-manage-the-gap-between-labels-using-geom-repel-in-r – Nader Mehri Oct 21 '20 at 20:43