Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Place Annotation at Center of Plot with ggplot2

Tags:

r

ggplot2

gtable

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?

like image 670
Tim_K Avatar asked Feb 13 '23 04:02

Tim_K


1 Answers

library(grid) # for textGrob

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

enter image description here

like image 54
baptiste Avatar answered Feb 14 '23 17:02

baptiste