2

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?

Ben S.
  • 3,415
  • 7
  • 22
  • 43
  • Would changing your code to read something like `facet_wrap(~carb + cyl, ncol=3)` still work for what you need? Or `facet_grid(carb ~ cyl)`? Or do you need to keep them separate? – Peter D Jul 21 '21 at 15:39
  • In my use case I'm generating the two different faceted plots from two different data sets, I just want the resulting facets to be the exact same size. But it's true I could bind them together. Conceptually they make sense as two distinct plots though. – Ben S. Jul 21 '21 at 16:37

1 Answers1

0

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]]))
user63230
  • 4,095
  • 21
  • 43