gtable
パッケージの関数を使用した別のソリューション。プロットを揃えますが、ストリップ テキストは保持します。関数を使用して、 のストリップ テキストの幅に等しいgtable
の右側に列を挿入します。p1
p2
library(ggplot2)
library(gridExtra)
library(gtable)
p1 <- ggplot(mtcars, aes(mpg, wt)) + geom_point()
p2 <- ggplot(mtcars, aes(mpg, wt)) + geom_point()
p2 <- p2 + facet_grid(cyl ~ .)
g1 = ggplotGrob(p1)
# gtable_show_layout(g1) # View the layout
# g1$widths # Get the widths of g1
g2 = ggplotGrob(p2)
# gtable_show_layout(g2) # View the layout
# g2$widths # Check the widths of g2
# Add new column to the right of g1 equal in width the strip width of g2.
# In g2, strip width is the 6th element the vector g2$widths
g1 <- gtable_add_cols(g1, g2$widths[6])
grid.arrange(g1, g2, ncol=1)
## But note that if the y-axis titles and/or labels take up different widths,
# the two plots are not aligned
p1 <- ggplot(mtcars, aes(mpg, wt)) + geom_point() +
theme(axis.title.y = element_text(vjust = .5, angle = 0, size = 30))
p2 <- ggplot(mtcars, aes(mpg, wt)) + geom_point()
p2 <- p2 + facet_grid(cyl ~ .)
g1 = ggplotGrob(p1)
g2 = ggplotGrob(p2)
g1 <- gtable_add_cols(g1, g2$widths[6]) # New column added to the right
grid.arrange(g1, g2, ncol=1) # Plots are not aligned
# Need to set widths to the maximums in the two plots,
# i.e., set g2 widths to be the same as g1 widths
g2$widths <- g1$widths
grid.arrange(g1, g2, ncol=1) # Plots are aligned
編集:または、baptiste で提案されているように、gtable
のrbind()
関数を使用します。
g1 = ggplotGrob(p1)
g2 = ggplotGrob(p2)
g1 <- gtable_add_cols(g1, g2$widths[6], 5) # New column added to the right
library(grid)
grid.draw(rbind(g1, g2, size = "first"))