Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
To modify a theme, add theme() with a corresponding
element_xx
object. These include element_line,
element_rect, and element_text. The following code shows how to
modify many of the commonly used theme properties (Figure 9-6):
library(gcookbook)# For the data set# Base plotp<-ggplot(heightweight,aes(x=ageYear,y=heightIn,colour=sex))+geom_point()# Options for the plotting areap+theme(panel.grid.major=element_line(colour="red"),panel.grid.minor=element_line(colour="red",linetype="dashed",size=0.2),panel.background=element_rect(fill="lightblue"),panel.border=element_rect(colour="blue",fill=NA,size=2))# Options for text itemsp+ggtitle("Plot title here")+theme(axis.title.x=element_text(colour="red",size=14),axis.text.x=element_text(colour="blue"),axis.title.y=element_text(colour="red",size=14,angle=90),axis.text.y=element_text(colour="blue"),plot.title=element_text(colour="red",size=20,face="bold"))# Options for the legendp+theme(legend.background=element_rect(fill="grey85",colour="red",size=1),legend.title=element_text(colour="blue",face="bold",size=14),legend.text=element_text(colour="red"),legend.key=element_rect(colour="blue",size=0.25))# Options for facetsp+facet_grid(sex ~.)+theme(strip.background=element_rect(fill="pink"),strip.text.y=element_text(size=14,angle=-90,face="bold"))# strip.text.x is the same, but for horizontal facets