public
Last active

  • Download Gist
set_panel_size.r
R
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
require(grid)
require(ggplot2)
 
 
set_panel_size <- function(p=NULL, g=ggplotGrob(p), width=unit(3, "cm"), height=unit(3, "cm")){
panel_index_w<- g$layout$l[g$layout$name=="panel"]
panel_index_h<- g$layout$t[g$layout$name=="panel"]
g$widths[[panel_index_w]] <- width
g$heights[[panel_index_h]] <- height
class(g) <- c("fixed", class(g), "ggplot")
g
}
 
print.fixed <- function(x) grid.draw(x)
 
left_width <- function(g){
axis_l_index <- g$layout$r[g$layout$name=="axis-l"]
ylab_index <- g$layout$r[g$layout$name=="ylab"]
g$widths[[axis_l_index]] + g$widths[[ylab_index]]
}
 
full_width <- function(g){
sum(g$widths)
}
 
 
align_plots <- function(..., width=unit(3, "cm"), height=unit(1, "null")){
 
pl <- list(...)
gl <- lapply(pl, set_panel_size, width=width, height=height)
left <- lapply(gl, left_width)
max_left <- max(do.call(unit.c, left))
 
widths <- lapply(gl, full_width)
max_width <- max(do.call(unit.c, widths))
lay <- grid.layout(nrow=length(gl), ncol=1)
vp <- viewport(layout=lay)
pushViewport(vp)
for(ii in seq_along(gl)){
pushViewport(viewport(layout.pos.row=ii))
pushViewport(viewport(x=unit(0.5, "npc") - 0.5*max_width + max_left - left[[ii]],
just="left", width=widths[[ii]]))
grid.draw(gl[[ii]])
upViewport(2)
}
upViewport()
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.