【问题标题】:saving multiple ggplots WITHOUT for loop在没有 for 循环的情况下保存多个 ggplots
【发布时间】:2020-11-05 21:32:11
【问题描述】:

使用ggsavefor 循环,我知道我可以将多个ggplots 保存到excel 电子表格中

例如来自Save multiple ggplots using a for loop

for (i in uniq_species) {

temp_plot = ggplot(data= subset(iris, Species == i)) + 
                 geom_point(size=3, aes(x=Petal.Length, y=Petal.Width )) + ggtitle(i)

ggsave(temp_plot, file=paste0("plot_", i,".png"), width = 14, height = 10, units = "cm")
}

但我想做的是避免循环,因为我有一个情节列表。 使用lapply 我有(我想)一个情节列表:

y.plot = lapply(1:nrow(df), function(row)
{
  ...
}

我的问题是,有没有办法从上面获取y.plot,然后将其中的所有图表推送到一个 Excel 电子表格中,而无需循环?

类似:ggsave(pic_path,plot=y.plot,width = 20,height=20,units='cm')

但这不起作用

【问题讨论】:

标签: r ggplot2


【解决方案1】:

也许,你正在寻找这个

dfs <- c("cars","pressure","mtcars")

my_plots <- list()
y.plot <- list()
en <- length(dfs)
y.plot <- lapply(1:en, function(i){
  
  df <- get(dfs[i])
  varname <- colnames(df)
  x=df[,1]
  y=df[,2]
  my_plots[[i]] <- ggplot(data=df,aes(x=x,y=y)) + geom_point() + 
    labs(x=varname[1], y=varname[2]) + theme_bw()
  
})

myplots <- do.call(grid.arrange, c(y.plot, ncol = en))

location <- "C:\\_My Work\\RStuff\\GWS\\"
ggsave(plot=myplots, file=paste0(location,"myplots.png"), width = 14, height = 10, units = "cm")

请注意,ggsave 目前可识别扩展名 eps/ps、tex (pictex)、pdf、jpeg、tiff、png、bmp、svg 和 wmf(仅限 Windows)。

如果你想把它保存到一个excel文件,你需要将图像保存为jpeg文件,然后使用openxslx,如下所示

ggsave(plot=myplots, file=paste0(location,"myplots.jpeg"), width = 14, height = 10, units = "cm")

pic_path <- paste0(location,"myplots.jpeg")

# Add to a new work book -------------
wb <- openxlsx::createWorkbook()
addWorksheet(wb, "Plots")
insertImage(wb, "Plots", pic_path)
openxlsx::saveWorkbook(wb, file=paste0(location,"myplots.xlsx"), overwrite = TRUE)

# Kill pic
unlink(pic_path)

【讨论】:

    猜你喜欢
    • 2014-11-19
    • 1970-01-01
    • 1970-01-01
    • 2021-11-12
    • 1970-01-01
    • 1970-01-01
    • 2020-08-10
    • 1970-01-01
    • 2014-05-26
    相关资源
    最近更新 更多