Skip to content

Instantly share code, notes, and snippets.

@baptiste
Created April 13, 2012 22:50
Show Gist options
  • Select an option

  • Save baptiste/2380653 to your computer and use it in GitHub Desktop.

Select an option

Save baptiste/2380653 to your computer and use it in GitHub Desktop.
fixed_width
library(ggplot2)
library(grid)
p1 <- qplot(1,1000, colour="test", linetype="longer legend") +
ylab("double\nline")
p2 <- qplot(1:10,1:10, colour="test") +
ylab("y") + guides(color="none")
## fixed_width <- function(p, width=unit(3, "cm"), draw=FALSE){
## gt <- ggplot_gtable(ggplot_build(p))
## panel_index <- gt$layout$r[gt$layout$name=="panel"]
## gt$widths[[panel_index]] <- width
## if(draw) grid.draw(gt)
## class(gt) <- c(class(gt), "grob")
## invisible(gt)
## }
## library(gridExtra)
## grid.arrange(fixed_width(p1), fixed_width(p2))
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)
}
set_panel_width <- function(g, width=unit(3, "cm")){
panel_index <- g$layout$r[g$layout$name=="panel"]
g$widths[[panel_index]] <- width
g
}
as.gtable <- function(p)
ggplot_gtable(ggplot_build(p))
align_plots <- function(..., width=unit(3, "cm")){
pl <- list(...)
gl <- lapply(pl, as.gtable)
gl <- lapply(gl, set_panel_width, width=width)
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()
}
grid.newpage()
align_plots(p1, p2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment