保留使用grid.arrange图的比例(Preserve proportion of graphs

2019-09-01 22:16发布

我试图安排使用多条曲线grid.arrange 。 它通过这本书做这项工作,并调用时:

p1 <- ggplot(subset(mtcars, cyl = 4), aes(wt, mpg, colour = cyl)) + geom_point() 
p2 <- ggplot(subset(mtcars, cyl = 8), aes(wt, mpg, colour = cyl)) + geom_point()

grid.arrange(p1, p2, ncol = 2)

我得到两个漂亮的曲线,对称的大小:

我的图表是指不同的参数,但它们共用同团体相同的颜色编码。 所以我想删除所有,但一个传说,找到一个好地方吧。

然而,当我尝试:

p3 <- ggplot(subset(mtcars, cyl = 8), aes(wt, mpg, colour = cyl)) + geom_point() + guides(colour=FALSE)

grid.arrange(p3, p2, ncol = 2)

没有传说中的情节得到(正确地)更大:

我想保持一定的尺寸(如x轴的长度),以保持相同跨越的曲线图。

我知道我可以在这里使用小面,但我还需要各种图表,(我认为)将很难使用方面实现结合起来..

是否有可能做到这一点的grid.arrange ? 任何其他的解决方案,可以帮助吗?

Answer 1:

几乎没有优雅简单@Josh的解决方案,但你可以用grid.arrange它允许您保留或指定地块的长宽比做到这一点,但你需要做一个tableGrob你的传奇。 我回答一个问题呈三角这里这是我得到了方便的代码使从GGPLOT2传奇tableGrob:

## Make a tableGrob of your legend
tmp <- ggplot_gtable(ggplot_build(p2))
leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
legend <- tmp$grobs[[leg]]

# Plot objects using widths and height and respect to fix aspect ratios
# We make a grid layout with 3 columns, one each for the plots and one for the legend
grid.newpage()
pushViewport( viewport( layout = grid.layout( 1 , 3 , widths = unit( c( 0.4 , 0.4 , 0.2 ) , "npc" ) ,heights = unit( c( 0.45 , 0.45 , 0.45 ) , "npc" ) , respect = matrix(rep(1,3),1) ) ) ) 
print( p1 + theme(legend.position="none") , vp = viewport( layout.pos.row = 1 , layout.pos.col = 1 ) )
print( p2 + theme(legend.position="none") , vp = viewport( layout.pos.row = 1, layout.pos.col = 2 ) )
upViewport(0)
vp3 <- viewport( width = unit(0.2,"npc") , x = 0.9 , y = 0.5)
pushViewport(vp3)
grid.draw( legend )
popViewport()



Answer 2:

试试这个,它采用cbind.gtable

grid.draw(cbind(ggplotGrob(p3), ggplotGrob(p2), size="last"))



文章来源: Preserve proportion of graphs using grid.arrange
标签: r ggplot2