【问题标题】:Avoid overlapping geom_point and geom_text in ggplot2避免在 ggplot2 中重叠 geom_point 和 geom_text
【发布时间】:2018-03-15 06:56:44
【问题描述】:

如何避免 ggplot2 中的这两层重叠?我尝试显示文本,使它们不位于点之上。

check_overlap 在避免文本重叠方面做得很好,但不会与其他图层重叠。

我也试过库geom_text_repel,但这个库不支持check_overlap,并显示每个数据点的文本。

但我不需要像check_overlap 那样为每个点都提供文本。

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)

【问题讨论】:

  • 你能去掉每个数据点的重复标签,然后使用来自ggrepel的geom_text_repel吗?
  • 我尝试过geom_text_repel,但它为geom_point 中的每个数据点显示了一个标签或文本,这是我不想要的。

标签: r ggplot2 scatter-plot geom-text


【解决方案1】:

geom_text_repel 不会为空字符串"" 创建文本标签。但是,文本标签会排斥未标记的数据点。

试试这个:

# 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))

【讨论】:

  • 这不是问题的一般解决方案。我们要避免 geom_text 和 geom_point 之间的重叠。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-29
  • 1970-01-01
  • 2019-01-22
相关资源
最近更新 更多