user3477071
user3477071

Reputation: 304

ggplot title location and color

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))

Upvotes: 2

Views: 1620

Answers (1)

Mike H.
Mike H.

Reputation: 14360

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

Upvotes: 2

Related Questions