Labelling points with ggplot2 and directlabels

 ̄綄美尐妖づ 提交于 2019-11-28 13:03:52

One way to avoid overlapping (to some degree at least) would be to offset each label by an amount which is determined by the closest point to it. So for example if a point's closest neighbouring point is directly to the right of it, its label would be placed to the left, etc.

# centre and normalise variables
test$yy  <- (test$y - min(test$y)) / (max(test$y) - min(test$y))
test$xx  <- (test$x - min(test$x)) / (max(test$x) - min(test$x))
test$angle <- NA
for (i in 1:nrow(test)) {
    dx <- test[-i, ]$xx - test[i, ]$xx
    dy <- test[-i, ]$yy - test[i, ]$yy
    j <- which.min(dx ^ 2 + dy ^ 2)
    theta <- atan2((test[-i, ]$yy[j] - test[i, ]$yy), (test[-i, ]$xx[j] - test[i, ]$xx))
    test[i, ]$angle <- theta + pi
}
sc <- 0.5
test$nudge.x <- cos(test$angle) * sc
test$nudge.y <- sin(test$angle) * sc

ggplot(test, aes(x=x, y=y)) + 
    geom_point(aes(colour=group)) + 
    geom_text(aes(x = x + nudge.x, y = y + nudge.y, label = ID), size = 3, show.legend = FALSE)

You can try playing around with the scaling parameter sc (the larger it is, the further away the labels will be from the points) to avoid overlapping labels. (I guess it may happen that not the same sc can be applied to all points to avoid overlaps - in that case you need to change the scaling parameter for each point maybe by defining sc using dx and dy).

It could be that ggrepel is better suited to the labelling of points in a scatterplot.

library(ggplot2)  # ggrepel requires ggpot2 v2.0.0
library(ggrepel)

ggplot(test, aes(x=x, y=y)) + 


geom_text_repel(aes(label = ID, color = group),  show.legend = FALSE,
                     box.padding = unit(0.45, "lines")) +

geom_point(aes(colour=group))

Maybe hjust and vjust is what you are looking for?

ggplot(test, aes(x=x, y=y)) + 
  geom_point(aes(colour=group)) + 
  geom_text(aes(label=ID), show_guide=F, hjust = 1.2, vjust = 0.5)

I think you can do this just by adjusting the jittering parameter -- ... position = position_jitter.... You may have to play around with it a tad since you've only given us 10% of your data:

ggplot(test, aes(x=x, y=y)) + 
  geom_point(aes(colour=group), position= position_jitter(width= 1.5, height= 1)) + 
  geom_text(aes(label=ID), show_guide=F, hjust = 1.2, vjust = -.5,
            position= position_jitter(width= 1.5, height= 1))

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!