Reputation: 53
I created a list of graphs using this function:
p.list = lapply(sort(unique(new$tree)), function(i){
ggplot(new[new$tree==i,], aes(age,height)) + geom_point() + theme_classic() + facet_wrap(~tree)})
This produced a list of 34 graphs, but I cannot view them. I am hoping to save them as separate files (save them as .jpeg images) in a single folder, and have each file labelled by "tree". Any advice on this is much appreciated!
Upvotes: 1
Views: 192
Reputation: 8107
A more tidyverse-y answer using the iris data as per Rui Barradas:
library(tidyverse)
library(glue)
p.list <- iris %>%
pull(Species) %>%
unique() %>%
sort() %>%
set_names() %>%
map(function(i){
ggplot(filter(iris, Species == i), aes(Sepal.Length, Sepal.Width)) +
geom_point() +
theme_classic()
})
iwalk(p.list, ~ ggsave(glue("{.y}.jpg"), .x, device = "jpeg"))
Upvotes: 0
Reputation: 76402
Here is a solution with ggsave
. It allows to specify the device as an argument.
tree_names <- sort(unique(iris$Species))
folder_name <- "~/tmp"
for(i in seq_along(p.list)){
flname <- paste0("tree_", tree_names[i], ".jpeg")
flname <- file.path(folder_name, flname)
ggsave(flname, plot = p.list[[i]], device = "jpeg")
}
#Saving 4.68 x 5.84 in image
#Saving 4.68 x 5.84 in image
#Saving 4.68 x 5.84 in image
Data
As a test data set I have used the following based on the built-in data set iris
.
p.list <- lapply(sort(unique(iris$Species)), function(i){
ggplot(iris[iris$Species == i,], aes(Sepal.Length, Sepal.Width)) +
geom_point() +
theme_classic()
})
Upvotes: 1
Reputation: 173793
You can do a simple loop:
for(i in seq_along(p.list)){
jpeg(filename = paste0("ggplot_", sort(unique(new$tree))[i], ".jpg"))
print(p.list[[i]])
dev.off()
}
This will write the files ggplot_1.jpg
, ggplot_2.jpg
etc to your home directory.
Upvotes: 3