Search code examples
rggplot2gridviewport

How to align vertically combined plots which are build with viewport


I would like to combine vertically two figures using viewport. Figures are created with ggplot and facet_grid(). The problem which arises is that the legend of the categorical variable differ in lengths. This result in plots with different width since the legend takes more places. I would like that the width of the plots are identically.

How can I solve this problem?

Here is an example of a figures with not aligned plots:

enter image description here

Here is the code to produce the figure:

# dataframe
x <- rep(1:10,2)
y <- x + rep(c(0,2),each=10)
sex <- rep(c("f","m"), each=10)
sex2 <- rep(c("fffffffff","mmmmmmmmm"), each=10)
df0 <- data.frame(x = x, y = y, sex = sex, sex2 = sex2)

# libraries
library("grid")
library("gridExtra")
library("ggplot2")

# Viewport
Layout <- grid.layout(nrow = 2, ncol = 1, heights = unit(c(1,1), c("null","null")))
vplayout <- function(x,y) {
       viewport(layout.pos.row=x, layout.pos.col=y)
}

# plot object
p1 <- ggplot(df0,aes(x = x, y = y,linetype=sex)) +
        geom_line() 

p2 <- ggplot(df0,aes(x = x, y = y,linetype=sex2)) +
        geom_line()         

# figures
tiff("test0.tiff", width=5, height=10, units="cm", res=300, compression = 'lzw')
grid.newpage()
pushViewport(viewport(layout= Layout))
print(p1 +  theme_bw(base_size=5), vp = vplayout(1,1))
print(p2 +  theme_bw(base_size=5), vp = vplayout(2,1))
dev.off()

Solution

  • You can use cowplot::plot_grid

    # figures
    library(cowplot)
    tiff("test0.tiff", width=5, height=10, units="cm", res=300, compression = 'lzw')
    grid.newpage()
    plot_grid(p1, p2, align = "v", nrow = 2, rel_heights = c(1/2, 1/2))
    dev.off()
    

    Note: I don't know how you set up df0 so cannot present exported plot.