2015-01-09 48 views
1

我知道在這個問題上的變化已經好幾次,但無法弄清楚如何將這些解決方案適用於這種特殊的挑戰:R:使用多個GGPLOT2情節d *層

我想用ggplot內部廣告*層呼叫繪製由v3變量分解的數據(數據框dat),並顯示v1中3個條件的數字變量v2。我想在一個頁面(PDF)的地塊,所以以爲我可以用dlply包含在隨後可能被輸送到中發現的「食譜爲R」 here

# Multiple plot function 
# 
# ggplot objects can be passed in ..., or to plotlist (as a list of ggplot objects) 
# - cols: Number of columns in layout 
# - layout: A matrix specifying the layout. If present, 'cols' is ignored. 
# 
# If the layout is something like matrix(c(1,2,3,3), nrow=2, byrow=TRUE), 
# then plot 1 will go in the upper left, 2 will go in the upper right, and 
# 3 will go all the way across the bottom. 
# 
multiplot <- function(..., plotlist=NULL, file, cols=1, layout=NULL) { 
    require(grid) 

    # Make a list from the ... arguments and plotlist 
    plots <- c(list(...), plotlist) 

    numPlots = length(plots) 

    # If layout is NULL, then use 'cols' to determine layout 
    if (is.null(layout)) { 
    # Make the panel 
    # ncol: Number of columns of plots 
    # nrow: Number of rows needed, calculated from # of cols 
    layout <- matrix(seq(1, cols * ceiling(numPlots/cols)), 
        ncol = cols, nrow = ceiling(numPlots/cols)) 
    } 

if (numPlots==1) { 
    print(plots[[1]]) 

    } else { 
    # Set up the page 
    grid.newpage() 
    pushViewport(viewport(layout = grid.layout(nrow(layout), ncol(layout)))) 

    # Make each plot, in the correct location 
    for (i in 1:numPlots) { 
     # Get the i,j matrix positions of the regions that contain this subplot 
     matchidx <- as.data.frame(which(layout == i, arr.ind = TRUE)) 

     print(plots[[i]], vp = viewport(layout.pos.row = matchidx$row, 
             layout.pos.col = matchidx$col)) 
    } 
    } 
} 
爲GGPLOT2的的multiplot包裝函數列表導致地塊

這裏是一個玩具數據幀:

set.seed(999) 
    dat <- data.frame(
     v1 = rep(c("A","B","C"),25), 
     v2 = runif(75,-1,2), 
     v3 = sample(c("hippo", "smoke", "meat"), 75, replace=T)) 

這是我能拿出最好的 - 它分別給出了情節,但犯規將它們合併,並給出了在控制檯一個奇怪的輸出。請注意,任何不使用multiplot()的解決方案對我來說都是一樣的好。

require(dplyr) 
require(ggplot2)  
p <- dlply(dat, .(v3), function(x){ 
     ggplot(x,aes(v1, v2)) + 
     geom_point()}) 

multiplot(plotlist=p, cols=2) 
+0

編輯:p應該給予plotlist論點的multiplot - 但它仍然不會工作 – user3375672 2015-01-09 21:32:33

+1

什麼問題與您的多槽解決方案?我不知道你的意思是「分開給出情節,但不合並它們」。我運行代碼時沒有輸出控制檯。你應該爲'dlply'加載'plyr',而不是'dplyr'。 – Gregor 2015-01-09 22:10:53

+0

@格雷戈爾:我要禁食(d)plyr;他們總是被加載(所以它的工作),並因此它需要plyr。這3個圖表顯示在圖形設備(RStudio)中,但分開(逐個)。然後在閱讀您的評論之後,我重新啓動了Rstudio,採購了多功能版(),並且無處可用。不知道那是什麼。然後,快樂(+1)爲您的評論。 – user3375672 2015-01-09 22:24:10

回答

3

下面是避免multiplot(),並使用所示herehere技術以不同的方式:

library(ggplot2) 
library(dplyr) 

results <- dat %>% 
    group_by(v3) %>% 
    do(plot = ggplot(., aes(v1, v2)) + geom_point()) 

pdf('all.pdf') 
invisible(lapply(results$plot, print)) 
dev.off() 
+0

是的,它一路走來。但我希望在幾頁(3)頁面中將所有(三個)地塊放入一個頁面,而不是一個子頁面。你能否對無形的東西發表評論(儘管這顯然意味着你在「內部」打印) – user3375672 2015-01-09 21:42:46