R: How to avoid overlapping labels

Viewed 4171

I have created a graphic with ggplot2 and some labels are overlapping. I want to show all labels without overlapping. Is that possible? How? I know there is an option "check_overlap" to geom_text where show or not show labels if there is o not an overlapping. But, this is not what I want. I want and need to show all the labels.

My code:

ggplot(data, aes(x=DRTG, y=ORTG)) +
  geom_point(colour = "#000000") + 
  ggtitle("Gráfico Liga DIA: Ratio Ofensivo / Ratio Defensivo (hasta jornada 8)") +
  geom_text(label=rownames(data), colour = "#000000", nudge_x = 0, nudge_y = 1, size = 4, fontface = "bold", check_overlap = F) +
  geom_point(data=pointMedia, aes(x=mediaDRTG, y=mediaORTG, colour="red", size = 1)) + 
  geom_vline(xintercept = pointMedia[, "mediaDRTG"], colour = "green") + 
  geom_hline(yintercept = pointMedia[, "mediaORTG"], colour = "blue") +
  geom_text(data=pointMedia, aes(x=mediaDRTG, y=mediaORTG, label="Liga DIA"), nudge_x = 0, nudge_y = 1, colour = "red", fontface = "bold") +
  theme(legend.position = "none") +
  geom_abline(intercept =0 , slope = 1, colour = "orange")+ xlim(70,115) + ylim(70,115)

And the image with overlapping on some of their labels:

enter image description here

1 Answers

Posting as an answer which was previously a comment.

Instead of passing just one constant value for nudge_y for geom_text:

ggplot(data, aes(x=DRTG, y=ORTG)) +
  geom_text(label=rownames(data), colour = "#000000", 
            nudge_x = 0, nudge_y = 1, size = 4, fontface = "bold", check_overlap = F)

... you may pass a full vector, like my_nudge_y:

my_nudge_y=c(1,1,...,0.6,1.2,...)
ggplot(data, aes(x=DRTG, y=ORTG)) +
  geom_text(label=rownames(data), colour = "#000000", 
  nudge_x = 0, nudge_y = my_nudge_y, size = 4, fontface = "bold", check_overlap = F)

which you use to individually tune the string positions.

Generally solving the overlapping is not very easy problem, because already with a relative small number of texts, the plotting area starts to fill with texts.

Related