Let's say I have a list of plots that I've created.
library(ggplot2)
plots <- list()
plots$a <- ggplot(car开发者_Go百科s, aes(speed, dist)) + geom_point()
plots$b <- ggplot(cars, aes(speed)) + geom_histogram()
plots$c <- ggplot(cars, aes(dist)) + geom_histogram()
Now, I would like to save all of these, labelling each with their respective names(plots) element.
lapply(plots,
function(x) {
ggsave(filename=paste(...,".jpeg",sep=""), plot=x)
dev.off()
}
)
What would I replace "..." with such that in my working directory the plots were saved as:
a.jpeg
b.jpeg
c.jpeg
probably you need to pass the names of list:
lapply(names(plots),
function(x)ggsave(filename=paste(x,".jpeg",sep=""), plot=plots[[x]]))
@kohske's answer is sensational! Below is the purrr 0.3.4
version for those who may prefer working within tidyverse
. Also, a temporary directory is created to hold the plots since ggsave
defaults to saving to the working directory.
map(names(plots), function(.x) {
ggsave(
path = "tmp/",
filename = paste0(.x, ".png"),
plot = plots[[.x]]
)
})
精彩评论