2017-09-06 42 views
0

我有一個代碼來繪製數據框中的一些數據。 當我運行沒有循環的代碼時,它可以工作,但是當我使用代碼執行代碼時,然後執行plots[[1]]plots[[2]]所有的圖都是相同的,但實驗室是不同的。ggplot2覆蓋保存在列表中的情節

我在做什麼錯了?由於

#-- Plots 
plots <- list() 
combinations <- combn(dim(ssgsea.diff)[2],2) 

for (i in 1:dim(combinations)[2]){ 

    fit <- lm(ssgsea.diff[,combinations[1,i]] ~ ssgsea.diff[,combinations[2,i]], 
      data = ssgsea.diff) 

    plot1 <- ggplot(ssgsea.diff) + 
    aes(ssgsea.diff[,combinations[1,i]], ssgsea.diff[,combinations[2,i]]) + 
    geom_point() 

    plot1 <- plot1 + 
    labs(x = names(ssgsea.diff)[combinations[1,i]], 
     y = names(ssgsea.diff)[combinations[2,i]]) + 
    geom_smooth(method="lm", col = "red") + 
    labs(title = paste("Adj R2 = ", signif(summary(fit)$adj.r.squared, 5), 
         " Slope =",signif(fit$coef[[2]], 5), 
         " Pval =",signif(summary(fit)$coef[2,4], 5))) 

    plots[[i]] <- plot1 
} 
+0

你可以在'dput()'表單中提供這裏使用的數據集嗎?或者,使用'datasets'包中的一個常用數據集來重現此問題。 –

+0

我無法提供數據集。但基本上,代碼中有一些東西,所有保存在'plot'列表中的圖都看起來像是最後創建的圖。即使代碼在循環外運行,也會發生這種情況。 – biorunner88

回答

1

由於沒有提供數據,我會試圖用R A共同數據,以證明:

data(airquality) 
ssgsea.diff <- as.data.frame(airquality) 

plots <- list() 
combinations <- combn(dim(ssgsea.diff)[2],2) 

使用原來的代碼重現問題。有後的15個地塊for循環的完成,&實際上他們都有着不同的標籤在同一張圖:

for (i in 1:dim(combinations)[2]){ 

    fit <- lm(ssgsea.diff[,combinations[1,i]] ~ ssgsea.diff[,combinations[2,i]], 
      data = ssgsea.diff) 

    plot1 <- ggplot(ssgsea.diff) + 
    aes(ssgsea.diff[,combinations[1,i]], ssgsea.diff[,combinations[2,i]]) + 
    geom_point() 

    plot1 <- plot1 + 
    labs(x = names(ssgsea.diff)[combinations[1,i]], 
     y = names(ssgsea.diff)[combinations[2,i]]) + 
    geom_smooth(method="lm", col = "red") + 
    labs(title = paste("Adj R2 = ", signif(summary(fit)$adj.r.squared, 5), 
         " Slope =",signif(fit$coef[[2]], 5), 
         " Pval =",signif(summary(fit)$coef[2,4], 5))) 

    plots[[i]] <- plot1 
} 

解決方案下面將導致存儲在列表中15個不同地塊(我還定義列索引首先,爲了使代碼更易讀):

for (i in 1:dim(combinations)[2]){ 

    # define column indices & column names first 
    C1 <- combinations[1, i]; C1.name <- names(ssgsea.diff)[C1] 
    C2 <- combinations[2, i]; C2.name <- names(ssgsea.diff)[C2] 

    fit <- lm(ssgsea.diff[, C1] ~ ssgsea.diff[, C2]) # no need to specify data here 

    plot1 <- ggplot(ssgsea.diff) + 
    aes_string(C1.name, C2.name) + geom_point() 

    plot1 <- plot1 + 
    labs(x = C1.name, y = C2.name) + 
    geom_smooth(method="lm", col = "red") + 
    labs(title = paste("Adj R2 = ", signif(summary(fit)$adj.r.squared, 5), 
         " Slope =", signif(fit$coef[[2]], 5), 
         " Pval =", signif(summary(fit)$coef[2, 4], 5))) 

    plots[[i]] <- plot1 
} 

rm(C1, C2, C1.name, C2.name, fit, plot1, i) 

說明:由於您指定ggplot審美映射的方式,所有的情節的對象是在當前循環結束時評估(即啦st)值爲i。更安全的方法是利用ggplot中的參數data,該參數將數據幀存儲在ggplot對象本身中,作爲拷貝而不是參考。當每個循環改變i時,ggplot對象中的數據副本不會改變。這兩篇文章的答案進一步討論了這一點:Storing ggplot objects in a list from within loop in R & Storing plot objects in a list