3
votes

Hello R and ggplot2 community!

I would like to horizontally align two plots, produced with ggplot2. One has both facets (and facet strips!) and legend, but the second hasn't. They share the same Y axis, which I would like to align. I'm ok to vertically align plots using their grobs' widths, but I couldn't figure it out with heights.

Here is a piece of code to support my question.

library( ggplot2 )
library( gridExtra )

plot_1 <- ggplot() +
  geom_point(
    data = iris,
    aes(
      x = Petal.Length,
      y = Petal.Width,
      colour = Sepal.Length 
      ) 
    ) +
  facet_grid(
    . ~ Species 
    ) +
  theme(
    legend.position = "bottom"
    )

plot_2 <- ggplot() +
  geom_point(
    data = iris,
    aes(
      x = Sepal.Width,
      y = Petal.Width
      )
    )

g1 <- ggplotGrob( plot_1 )
g2 <- ggplotGrob( plot_2 )

# Here, how to manipulate grobs to get plot_2 scaled to the plot_1's Y axis? (ie, with an empty area right of the plot_1's legend)

grid.arrange( g1, g2, ncol = 2 )

Do you know how to manipulate grobs' heights before grid.arrange()? (Any other suggestion is welcome!) Additionally, how to assign, say, two thirds of the total area to plot_1?

Note also that my real plots actually feature a coord_flip(), but I assumed it's not relevant for this question.

Thanks for your help!

1

1 Answers

1
votes

A simple solution is to create a blank panel:

blank<-grid.rect(gp=gpar(col="white"))

Then use grid.arrange in order to create a two column grid in which the second column actually consists of three rows.

grid.arrange(g1, arrangeGrob(blank,g2,blank,ncol=1,
heights=c(0.2,0.9,0.2)),ncol=2) 

Playing around with the heights argument should provide us with the desired result.

Regarding your additional question the heights and widthsarguments of grid.arrangeshould prove quite useful there aswell.