当标签相互重叠时自动改变标签的位置 geom_text

Automatically vary the positions of labels with geom_text when they overlie each other

我想创建一个带有标签而不是点的 ggplot 图,但它们相互重叠,因此您无法阅读它们。有没有一种很好的方法可以自动移动它们,使它们不会相互覆盖?

df = data.frame(x = c(1,4,5,6,6,7,8,8,9,1), y = c(1,1,2,5,5,5,3,5,6,4),
                label = rep(c("long_label","very_long_label"),5))
ggplot(data=df) + geom_text(data=df,aes(x=x, y=y, label = label))

谢谢

ggrepel(昨天发布给 CRAN - 2016 年 1 月 9 日)似乎 tailor-made 用于这些情况。但请注意:ggrepel 需要 ggplot2 v2.0.0

df = data.frame(x = c(1,4,5,6,6,7,8,8,9,1), y = c(1,1,2,5,5,5,3,5,6,4),
                label = rep(c("long_label","very_long_label"),5))

library(ggplot2)
library(ggrepel)

# Without ggrepel
ggplot(data = df) + 
   geom_text(aes(x = x, y = y, label = label))

# With ggrepel
ggplot(data = df) + 
     geom_text_repel(aes(x = x, y = y, label = label), 
             box.padding = unit(0.1, "lines"), force = 2,
             segment.color = NA)