0

I try to arrange two ggplots with different plot heights but same plot widths using the gridExtra package.

I have a solution for either the same width or the same height but I am unable to achieve both.

Here is my code:

require(ggplot2)
require(gridExtra)

set.seed(987)
dat <- data.frame(x = 1:100, 
              y1 = rnorm(100),
              y2 = rnorm(100)*1e6)

p1 <- ggplot(dat, aes(x = x, y = y1)) + 
  geom_point() + ylab("")

p2 <- ggplot(dat, aes(x = x, y = y2)) + 
  geom_point() + ylab("")

# Arrange Plots

# Version 1
# same widths, same heights
grid.draw(rbind(ggplotGrob(p1), ggplotGrob(p2), size = "last"))

# Version 2
# different heights, different widths
grid.arrange(p1, p2, ncol = 1, heights = c(2, 1)) 

Which results in this:

Version 1: Same widths but not different heights Version 1: Same widths but not different heights

Version 2: Different heights but not same plot widths Version 2: Different heights but not same widths

However, I want to have the combination: Same width, but different heights. Do you have any ideas of how to combine grid.draw and grid.arrange in this case?

David
  • 9,216
  • 4
  • 45
  • 78

1 Answers1

0

Thanks to @Gregor and his link to this questions, I could use most of the code of the other question with some minor changes. This is what it finally looks like:

gb1 <- ggplot_build(p1)
gb2 <- ggplot_build(p2)
# work out how many y breaks for each plot
n1 <- length(gb1$panel$ranges[[1]]$y.labels)
n2 <- length(gb2$panel$ranges[[1]]$y.labels)

gA <- ggplot_gtable(gb1)
gB <- ggplot_gtable(gb2)

# combine both plots (last should really be "pmax", it's an unfortunate bug)
g <- gtable:::rbind_gtable(gA, gB, "last")

# locate the panels in the gtable layout
panels <- g$layout$t[grepl("panel", g$layout$name)]
# assign new (relative) heights to the panels, based on the number of breaks
g$heights[panels] <- list(unit(n1*2,"null"), unit(n2, "null")) 
# notice the *2 here to get different heights 

grid.newpage()
grid.draw(g)
Community
  • 1
  • 1
David
  • 9,216
  • 4
  • 45
  • 78