0

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:

enter image description here

I did manage to add an annotation at the upper left corner with:

p <- p + annotation_custom(corr.label)

Which gives:

enter image description here

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.

shoosh_pap
  • 11
  • 2
  • It would be eaiser to help you if you provide [a minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) of the issue. As is one can only guess. So my guess is that your variable `corr.label` is already a textGrob. That would explain why using `annotation_custom(corr.label)` works and shows your desired label while `annotation_custom(grob)` shows `text[GRID.text.XXXX]`. – stefan Jan 15 '22 at 11:48
  • Your example code works fine and gives a plot with the desired label in the bottom right corner or to be more precise at x = .8, y = .3. – stefan Jan 15 '22 at 18:51
  • Really? Then I have no idea what the problem is. Thanks. – shoosh_pap Jan 16 '22 at 10:46

0 Answers0