2016-06-15 200 views
2

element_text()允許情節標題的位置的定製在圖的頂部使用hjust和vjust參數ggplot標題位置和顏色

ggplot(mtcars, aes(x=cyl, y=mpg)) + geom_point() + ggtitle("CYL vs MPG") + theme(plot.title=element_text(vjust=0.5, hjust=0.5)) 
  • 是有辦法的情節標題移到底部在x軸標籤下面的圖形居中?
  • 可以使用element_text()的顏色參數指定標題標題的前景顏色。
  • 有沒有方法可以設置繪圖標題的背景顏色?我想我的情節標題的信件有黑色的背景和白色的前景。
+0

[這](http://stackoverflow.com/questions/10014187/displaying-text-below-the-plot-generated-by-ggplot2)可能是有用的 – bouncyball

回答

2

是的,這是可能的。我沒有使用element_text,而是使用grid包中的textGrob。我認爲這對添加特定註釋更加靈活。這應該工作:

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

+0

非常詳細。謝謝。 – user3477071

+0

不知道我需要做什麼改變才能使黑白標題出現在劇情的頂部而不是底部。 – user3477071

+0

您只需要將margin改爲'plot.margin = unit(c(3,1,1,1),「lines」))'',然後更改'title_text'中的y值(來自negative to something> 1)to title_text < - textGrob(「Title」,x = 0.5,y = 1.1,gp = gpar(col =「white」,fill =「black」))' –