Search code examples
rggplot2geom-text

Why is geom_text() plotting the text several times?


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

overplotted text

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

no overplotted text

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

many many labels

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!


Solution

  • 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())
    

    enter image description here