2014-09-30 124 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")