There are other variations of this question, such as:
- R: place geom_text() relative to plot borders rather than fixed position on the plot
- ggplot2 annotate layer position in R
- Position ggplot text in each corner
In my opinion, these do not solve the general problem. The first simply pre-calculates the x and y ranges so that proportions can be used. The second two use the "trick" that one can pass +/- Inf
to position text in a given corner.
Here are two improvements I think would make for a more generalized solution:
- allow arbitrary positioning of a label via relative positioning
- works with variables calculated on the fly via
dplyr
(rules out pre-calculating ranges/ratios)
For sample data:
data.frame(
x = runif(100, min = sample(0:50, 1), max = sample(50:1000, 1)),
y = runif(100, min = sample(0:1000, 1), max = sample(1000:10000, 1))
) %>%
mutate(z = x + y) %>%
# code here to plot and put an annotation at e.g. x = 0.95, y = 0.1, relative to plot limits