r - The perils of aligning plots in ggplot -



r - The perils of aligning plots in ggplot -

question

how combine separate plots (ggplot2), different y-axis , different plot heights, yet retain alignment?

detail

when combining plots grid.arrange (method1), different y-axis units, not align. 1 way around utilize gtable (method2), cannot adjust relative height of plots.

example

require(ggplot2) #make 2 plots, different y axis x = c(1, 5) y= c(.1, .4) data1<-data.frame(x,y) top<- ggplot(data1, aes(x=x, y=y))+ geom_line() x = c(1, 5) y= c(100000, 400000) data2<-data.frame(x,y) bottom<- ggplot(data2, aes(x=x, y=y))+ geom_line() # method 1 - grid require(gridextra) grid.arrange(top, bottom, heights=c(.6,.3))

method 1 results in plot, misaligned due different length y axis labels:

#method 2 - gtable require(gtable) #extract grobs g1<-ggplotgrob(top) g2<-ggplotgrob(bottom) #bind tables g<-gtable:::rbind_gtable(g1, g2, "first") #remove row between plots g <- gtable_add_rows(g, unit(-1,"cm"), pos=nrow(g1)) #draw grid.newpage() grid.draw(g)

method 2 results in aligned plots, cannot adjust height of each plot.

thanks!

in gtable g, can set relative panel heights,

panels <- g$layout$t[grep("panel", g$layout$name)] g$heights[panels] <- lapply(c(1,2), unit, "null")

r ggplot2 alignment gridextra gtable

Comments

Popular posts from this blog

model view controller - MVC Rails Planning -

ruby on rails - Devise Logout Error in RoR -

html - Submenu setup with jquery and effect 'fold' -