使用包中的函数的另一种解决方案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
'srbind()
函数:
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"))