I have a ggplot with two facets, each containing the same custom added reference line. I want to add a single annotation label for each line, and to specify the location for each label in terms of the position on the overall plot.
I have tried adding the labels using annotate
but this adds a label to each individual facet.
How do I specify the location for a single label on the 'global', overall plotting area (analagous to how x
and y
behave for legend.position
in the example below) when facets are involved?
library(ggplot2)
p <- mtcars %>%
ggplot(aes(x = mpg, y = disp, colour = am)) +
geom_point() +
geom_vline(aes(xintercept = 15),
linetype = "dotted",
colour = "grey20") +
geom_vline(aes(xintercept = 25),
linetype = "dotted",
colour = "grey20") +
facet_wrap(~vs, nrow = 2)
# desired behaviour is to position labels using x and y of overall plot area, as per positioning of legend
p <- p +
# x and y refer to positions on overall plot here, not to values of variables within individual facets
theme(legend.position = c(x = 0.9, y = 0.5))
# failed attempt adds labels to each facet
p <- p +
# x and y refer to individual facets/values of x and y variables here
annotate("text", x = 15 , y = 0.5,
label = "This label\nshould be on midpoint of y",
colour = "grey50") +
annotate("text", x = 25 , y = 0.75,
label = "This label\nshould be 3/4 up plot",
colour = "grey50")
# show plot
p
Thanks!