4

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!

3 Answers 3

4

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]])
Sign up to request clarification or add additional context in comments.

Comments

4

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")

Comments

3

Here's an alternative strategy that I find more straight-forward (no need to fiddle with names and aes_string): melt the data to long format, and plot subsets

 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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.