Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to save ggplots as separate R-objects using For loop

It is intended to produce a number of plots and then merge them freely together using multiplot function. Please could you tell me how to save each plot as a separate R-object instead of having it printed as png file:

Examplary dataframe:

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

we use a for loop to produce pictures and save them in a file:

And the loop to change:

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()
}

Could you please help with changing the code in order to save each plot as R-object on my screen? Big Thanks in advance!

like image 739
Pawel Avatar asked Dec 20 '22 10:12

Pawel


2 Answers

I'm not sure what you are talking about with "merge them freely together using multiplot function", but you can save ggplot objects using the standard assignment operator. Like any R object, they can be stored in a list.

# 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]])
like image 103
arvi1000 Avatar answered Jan 17 '23 15:01

arvi1000


Instead of using a for loop, if you're gonna store in a list you could just use 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]]

You can even save the list in an RDS object:

saveRDS(gg_list, file = "./gg_list.RDS")
like image 32
Mario Becerra Avatar answered Jan 17 '23 16:01

Mario Becerra