1

How can I automatically and accurately make the width of the plotting area consistent in ggplot, when the labels vary between plots? For example, here are two plots (data and code follow), where the second has longer labels, so the width of the plotting area is made smaller to make room.

I know I can manually make the figure width wider on the second plot, but 1) I can't do that programmatically, and 2) it won't be exact unless I have lots of patience and time.

I don't even know how to search for what I'm calling here "the plotting area", so any assistance even in the terminology is helpful.

first plot is wider second plot is narrower

Here's code to generate the data and plots:

set.seed(5)
d1 <- expand.grid(x=LETTERS[1:3], g=letters[1:3], rep=1:10)
d1$y <- round(rnorm(nrow(d1), 10, 2), 1)
d2 <- expand.grid(x=LETTERS[1:3], g=letters[1:3], rep=1:10)
d2$y <- round(rnorm(nrow(d1), 10, 2), 1)
levels(d2$x) <- sapply(levels(d2$x), strrep, 10)
levels(d2$g) <- sapply(levels(d2$g), strrep, 10)

library(ggplot2)
p1 <- ggplot(d1) + aes(x, y, color=g) + geom_boxplot() + coord_flip()
p2 <- ggplot(d2) + aes(x, y, color=g) + geom_boxplot() + coord_flip()
ggsave("test1.pdf", p1)
ggsave("test2.pdf", p2)
Aaron left Stack Overflow
  • 36,704
  • 7
  • 77
  • 142

1 Answers1

1

Thanks to @BenBolker, I'm learning about cowplot. It has the align_plots function for this purpose (output not shown),

both2 <- align_plots(p1, p2, align="hv", axis="tblr")
p1x <- ggdraw(both2[[1]])
p2x <- ggdraw(both2[[2]])
save_plot("cow1.png", p1x)
save_plot("cow2.png", p2x)

and also plot_grid which saves the plots to the same file.

library(cowplot)
both <- plot_grid(p1, p2, ncol=1, labels = c("A", "B"), align = "v")
save_plot("cow.png", both)

enter image description here

I'm still going through cowplot functionality and will add to this answer if I find anything else useful, but if any reader knows of anything else, either in cowplot or not, don't let that stop you from adding another answer!

Aaron left Stack Overflow
  • 36,704
  • 7
  • 77
  • 142