How to guarantee exactly equal size of faceted plots across different plots?

Viewed 124

I'm doing something like the following. I tend to use cowplot for saving images of ggplot-generated plots but non-cowplot solutions are also fine. The first plot produces three facets (and one empty space) in a 2x2 arrangement, the second produces 6 facets in a 3x2 arrangement. I set base_height and base_width assuming a size of 2 square for each plot. In the images generated from the code below, the individual plots (each facet) are not quite the same size, across the two images.

library(ggplot2)
library(cowplot)

ggplot(mtcars, aes(x=mpg, y=hp))+
  geom_point()+
  facet_wrap(~cyl,ncol=2) +
  ggtitle("hp vs. mpg, by cyl") +
  theme_cowplot(font_size=10)

save_plot("car1.png", last_plot(), base_height=4, base_width=4)

ggplot(mtcars, aes(x=mpg, y=hp))+
  geom_point()+
  ggtitle("hp vs. mpg, by carb") +
  facet_wrap(~carb,ncol=3)+
  theme_cowplot(font_size=10)

save_plot("car2.png", last_plot(), base_height=4, base_width=6)

I tried including the png files in the post but they each get scaled differently so it would be misleading.

I know I could generate each facet separately as its own plot and use plot_grid, and then base_height and base_width would set the size of each plot on its own, but is there any way to use facet_wrap or facet_grid and set the absolute size when saved of each facet?

1 Answers

Does cowplot::align_plots work for you?

library(ggplot2)
library(cowplot)

p1 <- ggplot(mtcars, aes(x = mpg, y = hp)) + 
  geom_point() + 
  facet_wrap(~cyl, ncol = 2) + 
  ggtitle("hp vs. mpg, by cyl") + 
  theme_cowplot(font_size = 10)

p2 <- ggplot(mtcars, aes(x = mpg, y = hp)) + 
  geom_point() + 
  ggtitle("hp vs. mpg, by carb") + 
  facet_wrap(~carb, ncol = 3) + 
  theme_cowplot(font_size = 10)

twoplots <- align_plots(p1, p2, align = "hv", axis = "tblr")  #tblr' for aligning all margins
save_plot("car1.png", ggdraw(twoplots[[1]]))
save_plot("car2.png", ggdraw(twoplots[[2]]))
Related