2017-06-15 125 views
0

我已經從qplot或ggplot命名了實體列表(對象,列表,grobs?),它們自己渲染或保存得很好,但我無法弄清楚將它們作爲列表或向量來排列。我相信我的問題是通常提取列表對象,而不是使用ggplot2。如何從列表中保存或繪圖

library(ggplot2) 
library(grid) 
library(gridExtra) 

# Generate a named list of ggplots 
plotlist <- list() 
for(a in c(1:4)) { 
    for(b in c(1:4)) { 
     plotlist[[paste0("Z",a,b)]] <- 
      qplot(rnorm(40,a,b), 
        geom="histogram", 
        xlab=paste0("Z",a,b)) 
    } 
} 

# Arrange and display them 
# The following two lines work fine, so the plots are in there: 
plotlist[["Z12"]] 
ggsave(plot=plotlist[["Z12"]], filename="deletable.png") 

# The following two lines complain about not being 'grobs' 
grid.arrange(plotlist, widths=c(1,1), ncol=2) 
grid.arrange(unlist(plotlist), widths=c(1,1), ncol=2) 

可不知何故,我投他們作爲grobs沒有明確命名它們,或者找到一個替代選擇不公開,能讓GROB了呢?

+0

您可以包括一個[重複的例子(https://stackoverflow.com/questions/5963269/how-to-make-a-great-r -reproducible-例子)? – RobertMc

+0

@RobertMc我原來的帖子已經包含了一個可重複使用的例子,遵循Joris的指導原則,通過複製粘貼到控制檯中,除了library()語句。我會添加它們。 – mightypile

回答

1

使用lapply(plotlist, ggplot2::ggplotGrob)生成ggplot2 grobs列表。然後可以將這個列表清單傳遞給gridExtra::grid.arrange

例如:

library(ggplot2) 
library(gridExtra) 

plotlist <- list() 

for(a in c(1:4)) { 
    for(b in c(1:4)) { 
     plotlist[[paste0("Z",a,b)]] <- 
      qplot(rnorm(40,a,b), 
        geom="histogram", 
        xlab=paste0("Z",a,b)) 
    } 
} 

grid.arrange(grobs = lapply(plotlist, ggplotGrob), widths = c(1, 1), ncol = 2) 

enter image description here

+0

在測試此建議時,我發現僅通過明確使用「grobs = plotlist」而不是「plotlist」清除了錯誤。 「grobs = lapply(plotlist,ggplotGrob)」更加明確且完美。謝謝! – mightypile

相關問題