1

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()
M--
  • 25,431
  • 8
  • 61
  • 93
giordano
  • 2,954
  • 7
  • 35
  • 57
  • 1
    Look at some of the answer here (not the accepted one): https://stackoverflow.com/questions/26159495/align-multiple-ggplot-graphs-with-and-without-legends – MrFlick Jun 15 '17 at 14:55
  • 1
    `cowplot::plot_grid(p1, p2 align = "v", nrow = 2, rel_heights = c(1/2, 1/2))` – M-- Jun 15 '17 at 15:09
  • @Masoud: This function solved my problem. Put your answer on answer so I can accept your solution. – giordano Jun 15 '17 at 15:20

1 Answers1

1

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.

M--
  • 25,431
  • 8
  • 61
  • 93
  • I added the missing part to build df0 in the question: `df0 <- data.frame(x = x, y = y, sex = sex, sex2 = sex2)`. It was lost during the copy paste process. Thanks for help. – giordano Jun 16 '17 at 05:33