2014-09-30 35 views
1

它旨在生成多個圖並使用多點功能將它們自由合併在一起。請你能告訴我如何保存每個情節作爲一個單獨的R-對象,而不是讓它打印爲PNG文件:如何使用For循環將ggplots保存爲單獨的R對象

實施例一數據幀:

df1 <- data.frame(A = rnorm(50), B = rnorm(50), C = rnorm(50), group = rep(LETTERS[24:25], 25)) 

我們使用一個for循環出示圖片並保存在文件中:

,循環改變:

for(i in names(df1)[1:3]) { 
    png(paste(i, "png", sep = "."), width = 800, height = 600) 
    df2 <- df1[, c(i, "group")] 
    print(ggplot(df2) + geom_boxplot(aes_string(x = "group", y = i, fill = "group")) + theme_bw()) 
    dev.off() 
} 

請您,以便保存每個情節作爲R-對象我的屏幕上更改代碼幫助嗎? 提前致謝!

回答

4

我不確定你在說什麼「使用多功能函數自由合併它們」,但是可以使用標準賦值運算符保存ggplot對象。像任何R對象一樣,它們可以存儲在一個列表中。

# empty list for storage 
gg_list <- list() 

# if you must use a loop, loop through an indexing vector 
for(i in 1:3) { 
    # if you need the i'th name in df1 use: 
    names(df1)[i] 
    # assign your ggplot call to the i'th position in the list 
    gg_list[[i]] <- ggplot(...) 
} 

# Now you can recall the ggplots by reference to the list. 
# E.g., display the 1st one: 
print(gg_list[[1]]) 
+0

不錯 - 謝謝! ;) – xhudik 2016-10-04 15:25:07

3

下面是我找到更多的直截了當(無需姓名和aes_string撥弄)的另一種策略:融數據長格式,和劇情子集

df1 <- data.frame(A = rnorm(50), B = rnorm(50), C = rnorm(50), 
        group = rep(LETTERS[24:25], 25)) 

m = reshape2::melt(df1, id="group") 

## base plot, all the data 
p = ggplot(m) + geom_boxplot(aes(x = group, y = value)) + theme_bw() 

## split-and-apply strategy, using the `%+%` operator to change datasets 
pl = plyr::dlply(m, "variable", `%+%`, e1 = p) 

do.call(gridExtra::grid.arrange, pl) 
3

而不是使用的for循環,如果你在一個列表要去商店,你可以只使用lapply:

df1 <- data.frame(A = rnorm(50), 
        B = rnorm(50), 
        C = rnorm(50), 
        group = rep(LETTERS[24:25], 25)) 

gg_list <- lapply(names(df1)[1:3], function(i) { 
    df2 <- df1[, c(i, "group")] 
    ggplot(df2) + 
    geom_boxplot(aes_string(x = "group", y = i, fill = "group")) + 
    theme_bw() 
}) 

gg_list[[1]] 

你甚至可以將列表保存在一個RDS對象:

saveRDS(gg_list, file = "./gg_list.RDS")