2017-08-25 46 views
1

關於如何使用循環將ggplots排列在網格中,有lotsquestions。然而,我無法拼湊出我所追求的。用循環中的空格填充ggplot構面面板

我想在循環中繪製任意數量的等大小圖。最重要的是,我想使用facet_wrap並預先將數據分組(解釋爲什麼在下面)。這裏有一個例子:

df <- mtcars 
df$car <- rownames(df) 

ucar <- unique(df$car) 

# Split data into groups of n (6's here) 
split6s <- split(ucar, ceiling(seq_along(ucar)/6)) 

p <- list() 

# For each group of 6, plot something (mpg vs wt) faceted by group (car) 
for(i in 1 :length(split6s)){ 
    # Subset for group 
    temp <- subset(df, car %in% split6s[[i]])  

    # Save plot forcing facet with 1 row 
    p[[i]] <- ggplot(temp, aes(mpg, wt)) + geom_point() + 
       facet_wrap(~car, nrow = 1) 
} 

p[[5]] 

enter image description here

p[[6]] 

enter image description here

期望p[[6]]

enter image description here

我想這樣做,這樣我可以規範一些大小GR在,但使用方面,而不是隻是一起groin個人情節。

回答

1

我不確定這是否是您正在尋找的解決方案。

library(ggplot2) 
library(grid) 

df <- mtcars 
df$car <- rownames(df) 
ucar <- unique(df$car) 
split6s <- split(ucar, ceiling(seq_along(ucar)/6)) 

p <- list() 
for(i in 1 :length(split6s)){ 
    temp <- subset(df, car %in% split6s[[i]])  
    p[[i]] <- ggplot(temp, aes(mpg, wt)) + geom_point() + 
       facet_wrap(~car, nrow = 1) 
} 

g5 <- ggplotGrob(p[[5]]) 
g6 <- ggplotGrob(p[[6]]) 

# Delete left panels  
for (k in c(4:7, 16:19, 34:37)) { 
    g5$grobs[[k]] <- nullGrob() 
} 
# Copy Maserati and Volvo panels 
g5$grobs[[2]] <- g6$grobs[[2]] 
g5$grobs[[3]] <- g6$grobs[[3]] 
g5$grobs[[14]] <- g6$grobs[[6]] 
g5$grobs[[15]] <- g6$grobs[[7]] 
g5$grobs[[32]] <- g6$grobs[[12]] 
g5$grobs[[33]] <- g6$grobs[[13]] 
# Move left x-axis label 
g5$grobs[[39]]$children[[1]]$x <- unit(1/6, "npc") 

grid.draw(g5) 

enter image description here

+0

我認爲這給了我一個很好的開始。我需要玩數字,以便它自動知道要移除多少面板。在我的實際代碼中,最後一幅圖中的面板數量將根據我的數據而改變。 – Pete900