Avoid overlapping geom_point and geom_text in ggplot2

送分小仙女□ 提交于 2019-12-13 16:27:50

问题


How can I avoid that these 2 layers in ggplot2 overlap? I try to display the text so that they are not laying above the points.

check_overlap does a great job with avoiding that the text overlaps itself, but not with other layers.

I also tried the library geom_text_repel, but this library does not support check_overlap and shows the text for every data point.

But I need to not have the text for every point, like check_overlap does.

ggplot(dat, aes(x = CPI, y = HDI)) +
  geom_point(aes(color = Region), shape=21, size=4, position = "identity") +
  geom_text(data = dat, aes(label = Country), size=4, check_overlap = TRUE)

回答1:


geom_text_repel will not create text labels for the empty string "". However, the text labels will repel away from the unlabeled data points.

Try this:

# Hide text labels for the first 3 data points
idx <- c(1,2,3)

dat$CountryLabel      <- dat$Country
dat$CountryLabel[idx] <- ""

library(ggrepel)
ggplot(...) + geom_text_repel(data = dat, aes(label = CountryLabel))


来源:https://stackoverflow.com/questions/46555411/avoid-overlapping-geom-point-and-geom-text-in-ggplot2

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