2

element_text() allows customization of location of the plot title at the top of the plot using hjust and vjust arguments

ggplot(mtcars, aes(x=cyl, y=mpg)) + geom_point() + ggtitle("CYL vs MPG") + theme(plot.title=element_text(vjust=0.5, hjust=0.5))
  • Is there a way to move the plot title to the bottom of the plot, centered, below the x-axis label?
  • It is possible to specify foreground color of plot title using color argument of element_text().
  • Is there a way to set background color of the plot title? I would like letters of my plot title to have black background and white foreground.
ArunK
  • 1,731
  • 16
  • 35
user3477071
  • 194
  • 1
  • 13
  • [this](http://stackoverflow.com/questions/10014187/displaying-text-below-the-plot-generated-by-ggplot2) might be useful – bouncyball Jun 15 '16 at 13:56

1 Answers1

2

Yes it is possible. I didn't use element_text, but rather used textGrob from the grid package. I think this is more flexible for adding in your specific annotation. This should work:

 library(grid)
#Grob to store your text
title_text <- textGrob("Title",x=0.5,y=-0.2,gp=gpar(col="white",fill="black"))
#Dynamic Grob to store your background box - size adjusts to size of your title
title_box <- rectGrob(x=title_text$x,y=title_text$y, 
                      width = unit(3,"mm")+unit(1,"grobwidth",title_text),
                      height=unit(3,"mm")+unit(1,"grobheight",title_text),
                      gp=gpar(col="black",fill="black"))

#Plot, adding in the grobs
p<-ggplot(mtcars, aes(x=cyl, y=mpg)) + geom_point()+theme(plot.title=element_text(vjust=0.5, hjust=0.5),
                                                          plot.margin = unit(c(1,1,5,1), "lines")) +
  annotation_custom(grobTree(title_box,title_text))


#Creating Gtable so we can override clipping and place the on the bottom
gt <- ggplot_gtable(ggplot_build(p))
gt$layout$clip[gt$layout$name == "panel"] <- "off"

#Drawing our plot
grid.draw(gt)

enter image description here

Mike H.
  • 13,960
  • 2
  • 29
  • 39
  • Very elaborate. Thanks. – user3477071 Jun 15 '16 at 14:11
  • Not sure what change I need to make to bring black and white title appear on top of plot instead of bottom. – user3477071 Jun 15 '16 at 15:18
  • You just need to change your margin to something like `plot.margin = unit(c(3,1,1,1), "lines"))` and then change the y-value in the `title_text` (from negative to something >1) to `title_text <- textGrob("Title",x=0.5,y=1.1,gp=gpar(col="white",fill="black"))` – Mike H. Jun 15 '16 at 15:22