Jfly Jfly - 2 months ago 10
R Question

How to annotate lines like this in ggplot2?

See example:

Example

I hope I don't need to manually assign the coordinators of the texts. If this is too complicated to achieve in ggplot2, what are the alternatives in R? Or maybe even not in R?

Answer

As @Axeman says, ggrepel is a decent option. Unfortunately it will only avoid overlap with other labels, and not the lines, so the solution isn't quite perfect.

library(ggplot2)
install.packages("ggrepel")
library(ggrepel)

set.seed(50)
d <- data.frame(y = c(rnorm(50), rnorm(50, 5), rnorm(50, 10)), 
    x = rep(seq(50), times = 3), 
    group = rep(LETTERS[seq(3)], each = 50))

ggplot(d, aes(x, y, group = group, label = group)) + 
  geom_line() + 
  geom_text_repel(data = d[d$x == sample(d$x, 1), ], size = 10)
Comments