Thursday, 16 October 2014

arranging layout of lattice graphs using gridExtra package

gridExtra allows arranging multiple graphs in the device, even when those graphs are drawn from different data sources. This package only work for lattice and ggplot graphs.


library(lattice)
library(grid)
library(gridExtra)

dat<-aggregate(peri~perm,rock,sum)

dat1<-aggregate(rock[,c("peri","shape")],by=list(rock$perm),sum)
colnames(dat1)[1]<-"perm"


p1<-barchart(peri~factor(perm),dat,xlab="perm",ylab="peri",
main="data: rock aggregated 1",horizontal=FALSE,col="coral2",border="coral2")

p2<-xyplot(shape~factor(perm),dat1,xlab="perm",ylab="shape",col="seagreen2",
type="l",lty=1,lwd=2,main="data: rock aggregated 2")

p3<-xyplot(shape~peri,rock,xlab="peri",ylab="shape",col="maroon2",type="p",
cex=1.5,main="data: rock",pch=16)



grid.arrange(p1,p2,p3,ncol=1)





























grid.arrange(p2,arrangeGrob(p1,p3,widths=c(3/5,2/5),ncol=2),ncol=1)























To add the header or title,


grid.arrange(p2,arrangeGrob(p1,p3,widths=c(3/5,2/5),ncol=2),ncol=1,
main=textGrob("Rock",gp=gpar(cex=1.5,col="red")))


gridExtra versions later than 2.0.0 need to use "top" instead of "main" and "bottom" instead of "sub" for titles and subtitles respectively.


  



  
  
























To include a table in the display:


TBL<-summary(dat)

grid.arrange(arrangeGrob(
tableGrob(TBL, gp = gpar(cex = 0.8), show.rownames = FALSE, 
padding.h = unit(5, "mm")), 
p2, ncol = 2, widths = c(2/5, 3/5)), 
arrangeGrob(p1, p3, widths = c(3/5, 2/5), ncol = 2), ncol = 1,
main = textGrob("Rock", gp = gpar(cex = 1.5, col = "red")))



gridExtra versions later than 2.0.0 do not use gpar for tableGrob, hence the below code will need to be used instead.
  

grid.arrange(arrangeGrob(
tableGrob(TBL, theme = ttheme_default(core = list(fg_params = list(cex=0.8, hjust = 0.5)),
colhead = list(fg_params = list(cex=0.8))), rows = NULL), 
p2, ncol = 2, widths = c(2/5, 3/5)), 
arrangeGrob(p1, p3, widths = c(3/5, 2/5), ncol = 2), ncol = 1,
top = textGrob("Rock", gp = gpar(cex = 1.5, col = "red")))






























The gridExtra version >= 2.0.0 allows more formatting options for tableGrob. For example, changing colours of background:
  

grid.arrange(arrangeGrob(
tableGrob(TBL, theme = ttheme_default(core = list(fg_params = list(cex=0.8, hjust = 0.5),
bg_params = list(fill = c("tan", "wheat"))),
colhead = list(fg_params = list(cex = 0.8, col = "white"), bg_params = list(fill = "brown"))), rows = NULL), 
p2, ncol = 2, widths = c(2/5, 3/5)), 
arrangeGrob(p1, p3, widths = c(3/5, 2/5), ncol = 2), ncol = 1, 
top = textGrob("Rock", gp = gpar(cex = 1.5, col = "red")))
 
 







 














 
 
 
 

 

No comments:

Post a Comment