Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@gwb
Created August 3, 2012 21:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gwb/3251754 to your computer and use it in GitHub Desktop.
Save gwb/3251754 to your computer and use it in GitHub Desktop.
A low-level way to organize plots in a grid
"""
A better way uses the gridExtra package. This is mostly for future reference, in case gridExtra doesn't
handle a specific case.
"""
# Stacking plots in a grid
stack_plots <- function(gs, nrow, ncol, fout=NULL, add_opts){
# example: stack_plots(list(g1, g2, g3), 2, 2, function (x) opts(legend.position="bottom"))
if(length(fout) > 0){
pdf(fout, width=17, height=10)
}
grid.newpage()
pushViewport(viewport(layout=grid.layout(nrow,ncol)))
vplayout <- function(x, y) viewport(layout.pos.row = x, layout.pos.col = y)
curr_col = 1
curr_row = 1
for (i in seq(1, length(gs))){
ng <- gs[[i]] + add_opts()
print(ng, vp=vplayout(curr_row,curr_col))
if (curr_col==ncol){
curr_col = 1
curr_row = curr_row + 1
}else{
curr_col = curr_col + 1
}
}
if(length(fout) > 0){
dev.off()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment