I am trying to automatically put a custom annotation in the bottom right corner of a plot no matter the actual axes range. I have tried to do so with annotate from ggplot2 but it just didn't work. I am trying to work with annotation_custom from the grid package instead.
My code is long so I won't post all of it here, but rather the main problematic lines imo:
EDIT: I am adding a small dataframe for reproducibility
 df <- data.frame(col.a = c(1:5), col.b = c(23.3,5.2,61.0,9.0,3.25))
 # correlation calculation
 cor.result = df %>% cor.test(col.a, col.b, 
                  method = "spearman",
                  na.action=na.omit,
                  exact = FALSE)
 corr.label <- sprintf("r = %.3f\np = %g\n%s", cor.result$estimate, 
             cor.result$p.value, "spearman")
The result is something like:
 "r = -0.853\np = 0.003\nspearman"
Then I create a plot:
ttl = "Scatter Plot" # The title and subtitles are different in my code. 
sub.ttl = "sample id: patient zero"
p <- df %>% ggplot(aes(x = col.a, y = col.b) +   
  geom_smooth(color = "steelblue3", method = lm, formula = y ~ x) +
  geom_abline(aes(intercept=0, slope=1), color = 'grey45') +
  geom_point(color = "steelblue4", alpha = 0.5, size = 3) +
  labs(x = "HUMANnN2", y = "HUMAnN3", 
       title = ttl, 
       subtitle = sub.ttl) +
  theme(text = element_text(size = 12),
        plot.title = element_text(hjust = 0.5, size = 16),
        plot.subtitle = element_text(hjust = 0.5, size = 14)) 
And try to add an annotation:
grob <- grobTree(textGrob(label = corr.label, x = 0.8, y = 0.3))
p <- p + annotation_custom(grob)
The result is as follows:
I did manage to add an annotation at the upper left corner with:
p <- p + annotation_custom(corr.label)
Which gives:
Yes, it has to be at the bottom right corner. The annotation does show up when I switch corr.label with just a string of "hello". My guess is that grob doesn't pass newline characters accordingly.


