ggplot panel size and alignment across multiple markdown code chunks

I am looking for a method to do two things:

  1. standardize ggplot panel size and

  2. align panels.

And this should be done across multiple code chunks.

The approaches provided by patchwork::align_patches() and cowplot::align_plots() are both very close. However, they require that the ggplots be built all at once and then dispatched one at a time. Baptiste's egg method in this SO crosses code chunks, but then the alignment is lost (it's also hackish).

This seems like it should be a common use case - do some analysis, plot the result, manipulate the result, plot that, etc., and then have it all consistently sized and aligned along the y axes (assuming that is even possible...).

Reprex

---
output: html_document
---

```{r, include = FALSE}
knitr::opts_chunk$set(echo = TRUE, fig.align = "center")
```

```{r}
library(ggplot2)
data(mtcars)
```
```{r}
ggplot(mtcars) + 
  geom_boxplot(aes(gear, disp, group = gear)) + 
  ggtitle('Plot 2')
```

words, words, words

```{r}
ggplot(mtcars) + 
  geom_point(aes(hp, wt, colour = mpg)) + 
  ggtitle('Plot 3')
```

With this result:

Well, I suppose I'm going to answer this myself, perhaps whistling in the dark, but just in case...

Looks like I was a tad wrong about the patchwork solution. It does provide a method to make consistently sized and aligned plots across multiple code chunks using get_dim and set_dim. However, avoiding misbehaving plot elements (like guides floating over the plot panel) may require a kludge depending on the flavor of the first plot. That is, you may have to build a ggplot object that never gets called just to get the right dimensions for the plots you do want to show. There are other trade-offs as well. For example, set_dim does not apply to individual facet panels. Here's an reprex:

---
output: html_document
---

```{r, include = FALSE}
knitr::opts_chunk$set(echo = TRUE, fig.align = "center")
```

```{r}
library(ggplot2)
library(patchwork)
data(mtcars)
```

```{r}
base <- ggplot(mtcars) +
  geom_point(aes(mpg, disp, color = hp)) +
  ggtitle("Base Plot")

base_dimensions <- get_dim(base)
```



```{r}
bob <- ggplot(mtcars) + 
  geom_boxplot(aes(gear, disp, group = gear)) + 
  ggtitle('Plot 2')

set_dim(bob, base_dimensions)
```

words, words, words

```{r}
bill <- ggplot(mtcars) + 
  geom_point(aes(hp, wt, colour = mpg)) + 
  ggtitle('Plot 3')

set_dim(bill, base_dimensions)
```

The result:

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.