在R中,保存环境中的绘图列表。

4

我想使用ggsave()从我的R环境中保存所有的图形。 我如何在R中保存图形列表,然后将该列表用作ggsave()的输入?

我使用cars获取了一些图形,这里有示例:

PlotA <- ggplot(mtcars, aes(x=hp, y=mpg, color=cyl, shape=cyl)) +
  geom_point(size=3)

PlotB <- ggplot(mtcars, aes(x=hp, y=mpg, color=cyl, shape=cyl)) +
  geom_point(size=3) +
  geom_smooth(method="lm", aes(fill=cyl)) 

PlotC <- ggplot(mtcars, aes(x=hp, y=mpg)) +
  geom_point(size=3, aes(color=cyl, shape=cyl)) +
  geom_smooth(method="loess", color="black", se=FALSE) +
  geom_smooth(method="lm", aes(color=cyl, fill=cyl)) 
  • 我的尝试:
saveplots <- list()
saveplots <- ls(pattern = 'Plot')

### Save pngs ###

for(i in 1:length(saveplots)){
  ggsave(saveplots[[i]],
         file=paste0("Total", saveplots,".png"),
         width = 22, height = 11.5, units = "cm",
         path = "plots/")
}

  • 有些帖子对我有所帮助,但还不太够(ex1 ex2)。你们有什么想法吗?谢谢。
4个回答

2

你可以使用函数get从环境中获取对象。

for(i in 1:length(saveplots)){
  ggsave(plot = get(saveplots[[i]]),
         filename=paste0("Total", saveplots[[i]],".png"),
         width = 22, height = 11.5, units = "cm",
         path = "plots/")
}


1
太棒了!它正在工作!非常感谢您!!(只有一件事=我在原始帖子中打错了,现在我已经在路径中删除了 :)) - Larissa Cury

2

使用lapplylsget的另一种类似的方法:

plots_list <- lapply(ls(pattern="Plot"), get)

lapply(seq_along(plots_list), function(i) {
  ggsave(paste0("Total", i, ".png"), plots_list[[i]], width=22, height=11.5, units="cm", path = "plots/")
})

2
使用 mget
library(purrr)
library(dplyr)
library(stringr)
mget(savePlots) %>%
    iwalk(~ ggsave(str_c("Total", .y, ".png"), 
               .x, width = 22, height = 11.5, units = "cm", path = "plots/"))

1

如果您不知道/记得/关心所有 ggplot 的名称,可以尝试使用 saveplots <- lsclass('ggplot')。这是我的软件包(在CRAN上)"cgwtools"中提供的;源代码在此提供:

lsclass <- function (type = "numeric") 
{
    inlist <- ls(.GlobalEnv)
    classlist <- sapply(1:length(inlist), function(j) class(get(inlist[j])))
    tnams <- sapply(1:length(inlist), function(j) type %in% classlist[[j]])
    return(inlist[tnams])
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接