'ggplot2: Repel text using same x coordination

I'am trying use geom_text_repel and geom_point to repel all text but its only works witch same column (red repel with red, blue with blue but red won't repel with blue). Both columns use same x coordinate so I don't have idea how do this. There is sample code and effect:

data <-  data.frame(c(NA,NA,2.10,3.30,10,NA,3,NA,NA,0.80),c(4,NA,2,3.50,NA,NA,NA,NA,NA,1))
text <- c("text1","text2","text3","text4","text5","text6","text7","text8","text9","text10")
colnames(data) <- (c("data1","data2"))
ggplot(data,aes(x=seq(1,10), y=data)) + geom_point(color = "red",aes(y=data1)) + geom_point(aes(y=data2), color = 'blue') + 
geom_text_repel(aes(seq(1,10),data1, label = text)) + geom_text_repel(aes(seq(1,10),data2, label = text))

Failure plot



Solution 1:[1]

You have two geom_text_repel layers, one for each colour. These layers don't know anything about each other, so they will clash. You need a single layer, and to do this you should pivot your data to long format. This almost always makes plotting easier. It's also good practice to incorporate any external vectors you are using for the plot into your data frame (though do this before pivoting)

So if we add the external vectors and reshape like this:

data$text <- text
data$x    <- 1:10
data      <- tidyr::pivot_longer(data, cols = c("data1", "data2"),
                                 names_to = "set", values_to = "data")

The plotting code is straightforward, and none of the labels clash

ggplot(data, aes(x, data, color = set)) + 
  geom_point() + 
  geom_text_repel(aes(label = text)) +
  scale_color_manual(values = c("red", 'blue'))

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Allan Cameron