3
votes

Packages like cowplot and pathwork allow different plots to be aligned next/on each other with the plot-area dimensions synchronized, regardless of the space required by axis labels. e.g.

install.packages("ggridges")
install.packages("patchwork")
library(tidyverse)
library(ggridges)
library(patchwork)
p1 <- ggplot(iris, aes(Sepal.Length, Species)) + 
    geom_density_ridges() 
p2 <- ggplot(mtcars) + 
    geom_point(aes(mpg, disp))
p1 + p2  + plot_layout(ncol=1)  #different length of y axis label, same plot area size.

This is all good for html display. However, for journals, I and many others need to produce "stand-alone" plots. The graphs display data from different sources and have different axis label length. For a professional appearance, these plots also need to have the same plot-size. In article format, they will often appear if the same formatted page but with text between them, and

So, how do I make they need to be completely "aligned" (as in example above) but as SEPARATE r objects, so to speak.

How can I achieve this?

1
This is not easy. Although I hate myself a little bit suggesting it, it may be the easiest workaround to save the patchwork plot as pdf and then "cut" this to separate plots. Another option would be to use markdown and specify plot widths. There are many threads about this here, a good starting point may be here: stackoverflow.com/q/39634520/7941188. may also help: stackoverflow.com/questions/46840724/…. Or @dww 's answer on one of my own questions a while ago stackoverflow.com/a/48671508/7941188tjebo
P.S. What I am doing is printing my plots usually as pdf with the same widths dimension (I usually use ggsave(plot = x, filename = 'x.pdf', width = ..., height = ...). will result in very similar axis lengths, but not exactly the same. If the objects are spread over several pages, this is likely not going to be noticeable, so this would be the easiest option.tjebo
@Tjebo thanks for the tip, I do things manually sometimes as well, you are not alone :p. See the suggestion below for a solution and happy hollidaysNils

1 Answers

2
votes

Inside cowplot, there is a function align_margin that aligns your left and right margins in a list of ggplot grobs.

We include a few more plots:

p1 <- ggplot(iris, aes(Sepal.Length, Species)) + 
    geom_density_ridges() 
p2 <- ggplot(mtcars) + 
    geom_point(aes(mpg, disp))
p3 <- ggplot(PlantGrowth) + 
    geom_boxplot(aes(group, weight))
p4 <- ggplot(USArrests) + 
    geom_point(aes(Assault, UrbanPop))

With some slight modification from the vignette:

grobs <- lapply(list(p1, p2, p3,p4), as_grob)
plot_widths <- lapply(grobs, function(x) {x$widths})
aligned_widths <- align_margin(align_margin(plot_widths, "first"),"last")
# reset widths
for (i in seq_along(plots)) {
       grobs[[i]]$widths <- aligned_widths[[i]]
     }

To get all in a page:

plot_grid(plotlist = grobs, ncol = 1)

To get individual:

grid.draw(grobs[[1]])