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!
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]])
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With