element_text()
允许使用hjust和vjust参数自定义绘图顶部的绘图标题位置
ggplot(mtcars, aes(x=cyl, y=mpg)) + geom_point() + ggtitle("CYL vs MPG") + theme(plot.title=element_text(vjust=0.5, hjust=0.5))
答案 0 :(得分:2)
是的,这是可能的。我没有使用element_text
,而是使用textGrob
包中的grid
。我认为这对于添加特定注释更加灵活。这应该有效:
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)