4

I'd like to place an annotation at the center of a several ggplot objects.

I've researched and found a few similar questions such as here: Relative positioning of geom_text in ggplot2?

So far, the only answer I've found is to manipulate the absolute range (e.g. ",y = ymax/2").

I'd like to add the annotation layer in a loop, prior to printing to .pdf. I can place the annotation in the corners by using +/- Inf, as follows:

plot.list<-list()
g<- qplot(1,1)

plot.list[[length(plot.list)+1]]<-g
plot.list[[length(plot.list)+1]]<-g

pdf("MyReport.pdf"
    ,width = 14
    ,height=8.5
    ,paper="a4r")
for(i in 1:length(plot.list)){
  print(plot.list[[i]]+
          annotate("text",x=Inf,y=Inf,hjust=1,vjust=1
                   ,label="PLEASE DO NOT DISTRIBUTE"
                   ,fontface="bold",color="darkred",alpha=0.3))
}
dev.off()

How can I place the annotation at the center, rather than the corner?

Community
  • 1
  • 1
Tim_K
  • 659
  • 10
  • 24
  • `annotation_custom` [should work](http://blog.ggplot2.org/post/23537012922/adding-watermarks-to-plots) – baptiste Aug 25 '14 at 14:28
  • @baptiste - thanks for pointing me in the right direction. The help text for annotation_custom is unclear on how to do non-relative positioning (i.e., not data dependent). I'm trying something like: plot.list[[i]]+annotation_custom(grob=splitTextGrob("PRELIMINARY, PLEASE DO NOT DISTRIBUTE"),xmin = 1,xmax=5, ymin = 1, ymax=100) BUT this is still dependent on the x and y scales – Tim_K Aug 25 '14 at 15:50
  • 1
    if you use +/- Inf as limits, the grob should span the whole plot, so the text should place itself in the centre – baptiste Aug 25 '14 at 16:07

1 Answers1

9
library(grid) # for textGrob

qplot(1,1) +
    annotation_custom(grid::textGrob("there"), 
                      xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf) 

enter image description here

divibisan
  • 11,659
  • 11
  • 40
  • 58
baptiste
  • 75,767
  • 19
  • 198
  • 294
  • Error: annotation_custom only works with Cartesian coordinates Run `rlang::last_error()` to see where the error occurred. Looks like it doesn't work anymore. Hooray... – Benbob Jul 27 '20 at 05:15