使用grid.arrange保留图形的比例

rad*_*dek 19 r ggplot2

我正在尝试使用安排多个地块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)
Run Code Online (Sandbox Code Playgroud)

我得到两个很好的图,大小对称:

在此输入图像描述

我的图表引用了不同的参数,但它们对组共享相同的颜色编码.所以我想删除除了一个以外的所有传奇,找到一个不错的地方.

但是,当我尝试:

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

grid.arrange(p3, p2, ncol = 2)
Run Code Online (Sandbox Code Playgroud)

没有图例的情节得到(正确)更大:

在此输入图像描述

我想保持大小(作为x轴的长度)在图表中保持相同.

我知道我可以在这里使用faceting,但是我还需要结合使用facet(我认为)很难实现的各种图形.

有可能做到grid.arrange吗?还有其他解决方案吗?

Jos*_*ien 24

试试这个,它使用cbind.gtable:

grid.draw(cbind(ggplotGrob(p3), ggplotGrob(p2), size="last"))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • +1我有大约20行代码我正要粘贴以通过一些手动摆弄来完成同样的事情.我*希望*我之前知道`cbind.gtable`.谢谢. (2认同)

Sim*_*lon 12

不像@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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 我觉得respsect说法有点混乱,但本质上我认为它的长宽比为每个视口的矩阵,所以我们有`1,1,1`因为我们有1行3列,我们希望有一个1:1的纵横每个比例.这可能不是*相当*它如何工作,但它帮助我!宽度单位不能*总和为1.您可以在小于绘图区域的宽度内挤压它们."npc"从0到1,其中0表示绘图区域的左边缘或底部,1表示右边缘或顶部,0.5表示中心.相应缩放.] (2认同)