I am running a lot of graphs across different subsets of data, using the split function with the lapply function.
My problem is: How do I easily save all the graphs? Ideally I want to name each fileby the title of the graph (Indicating the subset of data).
data("mtcars")
split <- split(mtcars, list(mtcars$gear, mtcars$am))
my_plot <- function(mtcars) {
ggplot(mtcars, aes(x=mpg, y=cyl)) +
geom_point() +
labs (title= paste(unique(mtcars$gear), paste("- ", unique(mtcars$am)))) }
lapply(split, my_plot)
Thus far, I have been saving the temporary directory (But this is a lot of manual labour)
plots.dir.path <- list.files(tempdir(), pattern="rs-graphics", full.names = TRUE);
plots.png.paths <- list.files(plots.dir.path, pattern=".png", full.names = TRUE)
file.copy(from=plots.png.paths, to="......")
You could include ggsave
in your function, then we would loop over the names()
of split
instead:
data("mtcars")
library(ggplot2)
split <- split(mtcars, list(mtcars$gear, mtcars$am))
my_plot <- function(x) {
p <- ggplot(split[[x]], aes(x=mpg, y=cyl)) +
geom_point() +
labs (title= paste(unique(split[[x]][["gear"]]), paste("- ", unique(split[[x]][["am"]]))))
ggsave(paste0("my_path/mtcars_", x, ".png"))
p
}
lapply(names(split), my_plot)
Alternatively we could use a slightly different workflow with purrr::map
and purrr::iwalk()
. First we create a list of plots with purrr::map
and than loop over the named lists of plots using purrr::iwalk()
to save them:
library(purrr)
my_plot <- function(df, nm) {
ggplot(df, aes(x=mpg, y=cyl)) +
geom_point() +
labs (title= paste(unique(df[["gear"]]), paste("- ", unique(df[["am"]]))))
}
# save plots to list
plots <- map(split, my_plot)
# loop over plots and save
iwalk(plots, ~ ggsave(paste0("my_path/mtcars_", .y, ".png"),
plot = .x))
Created on 2023-02-16 by the reprex package (v2.0.1)