Skip to content

Instantly share code, notes, and snippets.

@baptiste
Last active December 26, 2015 01:19
Show Gist options
  • Save baptiste/7070429 to your computer and use it in GitHub Desktop.
Save baptiste/7070429 to your computer and use it in GitHub Desktop.
arrange grobs in a gtable from a layout specification
gtable_layout <- function(grobs, widths = NULL, heights = NULL,
m, ...){
if(is.null(widths))
widths <- unit(rep(1,ncol(m)), "null")
if(is.null(heights))
heights <- unit(rep(1,nrow(m)), "null")
cells <- sort(unique(c(m)))
## left/right/top/bottom borders for given id
range_cell <- function(ii){
ind <- which(m == ii, arr.ind=TRUE)
c(l=min(ind[,"col"]),
r=max(ind[,"col"]),
t=min(ind[,"row"]),
b=max(ind[,"row"]))
}
layout <- data.frame(t(sapply(cells, range_cell)))
gt <- gtable(widths = widths, heights = heights, ...)
gtable_add_grobs <- gtable_add_grob # alias
with(layout, gtable_add_grobs(gt, grobs, t=t, l=l, b=b, r=r))
}
gl <- lapply(1:9, function(ii) grobTree(textGrob(ii), rectGrob()))
gt <- gtable_layout(gl, m=rbind(c(1,1,1,2,3),
c(1,1,1,4,5),
c(6,7,8,9,9)))
grid.draw(gt)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment