为什么geom_text()多次绘制文本?

时间:2019-02-27 08:04:10

标签: r ggplot2 geom-text

请考虑以下最小示例:

library(ggplot2)
library(ggrepel)
ggplot(mtcars) +
  aes(x = mpg, y = qsec) +
  geom_line() +
  geom_text(x = 20, y = 20, label = "(20,20)")

overplotted text

我想您可以很容易地看到文本((20,20))过度绘制(实际上,我不知道这是不是正确的词。我的意思是该文本在一个位置多次绘制)

如果我使用annotate(),则不会发生:

ggplot(mtcars) +
  aes(x = mpg, y = qsec) +
  geom_line() +
  annotate("text", x = 20, y = 20, label = "(20,20)")

no overplotted text

“那么,为什么不使用annotate()?”你可能会问。实际上,我不想使用文本作为注释,而是使用标签。而且我还想使用{ggrepel}包来避免过度绘图。但是看看当我尝试这样做时会发生什么:

ggplot(mtcars) +
  aes(x = mpg, y = qsec) +
  geom_line() +
  geom_label_repel(x = 20, y = 20, label = "(20,20)")

many many labels

同样,绘制了许多标签,{ggrepel}在防止标签重叠方面做得很好。但我只希望一个标签指向特定位置。我真的不明白为什么会这样。我仅为xylabel提供了一个值。我还尝试了data = NULLinherit.aes = F并将这些值放入aes()中的geom_label_repel()中无效。我怀疑标签的数量与mtcars中的行数一样。对于我的实际应用程序,这真的很糟糕,因为在相应的数据集中有很多行。

您能否在这里帮助我,并简要说明为什么会发生这种情况以及您的解决方案为何起作用?非常感谢!

2 个答案:

答案 0 :(得分:2)

geom_textgeom_label_repel每行添加一个标签。因此,您可以为注释几何提交单独的数据集。例如:

library(ggplot2)
library(ggrepel)
ggplot(mtcars, aes(mpg, qsec)) +
    geom_line() +
    geom_label_repel(aes(20, 20, label = "(20,20)"), data.frame())

enter image description here

答案 1 :(得分:2)

在geom_text中添加“ check_overlap = TRUE”,以防止过度绘图。

library(ggplot2) 

ggplot(mtcars) +
        aes(x = mpg, y = qsec) +
        geom_line() +
        geom_text(x = 20, y = 20, label = "(20,20)", check_overlap = TRUE)

enter image description here

相关问题