Why is geom_text() plotting the text several times?

99封情书 提交于 2020-05-13 07:35:15

问题


Please consider the following minimal example:

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

I guess you can see pretty easily that the text "(20,20)" is heavily overplotted (actually, I don't know whether that's the correct word. I mean that the text is plotted several times at one location).

If I use annotate(), this does not happen:

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

"So, why don't you use annotate() then?" you might ask. Actually, I don't want to use text for annotation but labels. And I also want to use the {ggrepel} package to avoid overplotting. But look what happens, when I try this:

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

Again, many labels are plotted and {ggrepel} does a good job at preventing them from overlapping. But I want only one label pointing at a specific location. I really don't understand why this happens. I only supplied one value for x, y and label each. I also tried data = NULL and inherit.aes = F and putting the values into aes() within geom_label_repel() to no effect. I suspect that there are as many labels as there are rows in mtcars. For my real application that's really bad because I have a lot of rows in the respective dataset.

Could you help me out here and maybe give a short explanation why this happens and why your solution works? Thanks a lot!


回答1:


geom_text or geom_label_repel adds one label per row. Therefore you can submit a separate dataset for annotation geom. For example:

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




回答2:


Add "check_overlap = TRUE" to geom_text to stop overplotting.



来源:https://stackoverflow.com/questions/54900695/why-is-geom-text-plotting-the-text-several-times

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