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!
Add "check_overlap = TRUE" to geom_text to prevent overplotting.
library(ggplot2)
ggplot(mtcars) +
aes(x = mpg, y = qsec) +
geom_line() +
geom_text(x = 20, y = 20, label = "(20,20)", check_overlap = TRUE)
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With