当geom_text相互叠加时,会自动改变标签的位置

时间:2016-01-06 21:43:06

标签: r graphics ggplot2 label geom-text

我想创建一个带有标签而不是点的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))

谢谢

1 个答案:

答案 0 :(得分:3)

ggrepel(昨天发布到CRAN - 2016年1月9日)似乎是针对这些情况量身定做的。但请注意: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) 

enter image description here