I am struggling to modify ggplot2 annotate(). All I want to do, is create a slightly modified annotate() function (say, annotate_new()) which automatically places annotations in the top left corner with a certain text size.
Below, please find my try which somehow doesn't work:
annotate_new <-
function (geom, xmin = NULL, xmax = NULL,
ymin = NULL, ymax = NULL, xend = NULL, yend = NULL,
x=NULL, y=NULL, parse=TRUE, size = 12, ...,
na.rm = FALSE) {
position <- compact(list(xmin = xmin, xmax = xmax,
xend = xend, ymin = ymin, ymax = ymax, yend = yend,
x = -Inf, y = Inf,
hjust = 0, vjust = 1))
aesthetics <- c(position, list(...))
lengths <- vapply(aesthetics, length, integer(1))
n <- unique(lengths)
if (length(n) > 1L) {
n <- setdiff(n, 1L)
}
if (length(n) > 1L) {
bad <- lengths != 1L
details <- paste(names(aesthetics)[bad], " (",
lengths[bad], ")", sep = "", collapse = ", ")
stop("Unequal parameter lengths: ", details, call. = FALSE)
}
data <- vctrs::new_data_frame(position, n = n)
layer(geom = "text",
params = list(na.rm = na.rm, ...), stat = StatIdentity,
position = PositionIdentity, data = data, mapping = aes_all(names(data)),
inherit.aes = FALSE, show.legend = FALSE)
}
ggplot(mpg, aes(displ, hwy)) +
geom_point() +
annotate_new(label = corr_eqn(mpg$hwy, mpg$displ))
This creates:
Somehow, the text size isn't adjustable... Would really appreciate your help!


