简体   繁体   中英

grid.arrange(): arrange 3 plots neatly

I want to arrange 3 square ggplots showing one of them bigger and the other two smaller alongside with the first one.

Here is my attempt:

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

Basically, I want the top border of the small plot2 to be level with the top border of the big plot1, and the bottom border of plot3 to be level with the bottom border of plot1. Also ggtitle1 should be level with ggtitle 2.

When I save my triple plot (even keeping the desired aspect ratio)

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

I get something like this

在此输入图像描述

Any ideas on how to manage the neat arrangement?

I always put everything in a variable with the arrangeGrob function and save this object with 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.

Be aware, something changed with the new gridExtra package and the syntax has changed, but with version 0.9.1 this works nicely.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM