【问题标题】:grid.arrange(): arrange 3 plots neatlygrid.arrange():整齐排列3个地块
【发布时间】:2015-08-13 14:19:56
【问题描述】:

我想安排 3 个方形 ggplots,其中一个较大,另外两个较小,与第一个一起显示。

这是我的尝试:

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))

基本上,我希望小 plot2 的上边框与大 plot1 的上边框齐平,而 plot3 的下边框与 plot1 的下边框齐平。 ggtitle1 也应该与 ggtitle 2 处于同一水平。

当我保存我的三重图时(即使保持所需的纵横比)

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()

我得到了这样的东西

关于如何管理整齐排列的任何想法?

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    我总是使用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)
    • 说实话,我并没有完全阅读我刚刚意识到的问题,但是是的,widths=c(2,1) 解决了它:-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多