grid.arrange(): 整齐排列3个图表

3
我希望安排3个正方形的ggplot图,其中一个较大,另外两个较小,与第一个图并排显示。
以下是我的尝试:
gg1 <- ggplot(mtcars,aes(x=hp,y=mpg))+
        geom_point(aes(color=factor(cyl)),alpha=.5)+
        stat_smooth(method='lm', se=F, color='red')+
        ggtitle('plot 1')+
        theme_bw()+
        theme(aspect.ratio=1,
              legend.position = c(1, 1), 
              legend.justification = c(1,1), 
              legend.background = element_rect(colour = NA, fill = NA))


gg2 <- ggplot(mtcars)+
        geom_density(aes(x=hp, color=factor(cyl)))+
        ggtitle('plot 2')+
        theme_bw()+
        theme(aspect.ratio=1,
              legend.position = c(1, 1), 
              legend.justification = c(1,1), 
              legend.background = element_rect(colour = NA, fill = NA))


gg3 <- ggplot(mtcars)+
        geom_density(aes(x=mpg, color=factor(cyl)))+
        ggtitle('plot 3')+
        theme_bw()+
        theme(aspect.ratio=1,
              legend.position = c(1, 1), 
              legend.justification = c(1,1), 
              legend.background = element_rect(colour = NA, fill = NA))

grid.arrange(arrangeGrob(gg1), 
             arrangeGrob(gg2,gg3, ncol=1), 
             ncol=2, widths=c(1,1))

基本上,我希望小图2的顶部边框与大图1的顶部边框水平对齐,同时将plot3的底部边框与plot1的底部边框水平对齐。此外,ggtitle1应该与ggtitle2水平对齐。

当我保存我的三合一图时(即使保持所需的宽高比),

png(file = 'test.png',width=900,height=600)
grid.arrange(arrangeGrob(gg1), 
             arrangeGrob(gg2,gg3, ncol=1), 
             ncol=2, widths=c(1,1))
dev.off()

我得到了这样的东西

在这里输入图片描述

有什么想法来管理整齐的安排吗?

1个回答

2

我总是使用arrangeGrob函数把所有东西放入一个变量中,并使用ggsave保存该对象。

a <- arrangeGrob(arrangeGrob(gg1), arrangeGrob(gg2,gg3, ncol=1), ncol=2, widths=c(2,1)) 
# big plot should be twice wider than two small ones
ggsave('~/Downloads/jnk.pdf',a)
ggsave('~/Downloads/jnk.png',a) #in case of png file.

请注意,新的gridExtra包发生了一些变化,语法也有所改变,但是在版本0.9.1中,这个问题已经得到了很好的解决。


那并不能解决问题,而且无论如何,我想要宽度类似于c(2,1)。 - ikashnitsky
说实话,我没有完全读懂这个问题,但是我意识到 widths=c(2,1) 可以解决它 :-) - drmariod

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接