循环内时如何将图存储在列表中? [英] How to store plots in a list when inside a loop?

查看:77
本文介绍了循环内时如何将图存储在列表中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在循环内工作,我想将图表保存在列表中,以便可以将它们一起绘制为.pdf.问题在于该列表未正确填充,并使用上次运行的结果重新更新.因此,最后我得到的是一个包含五个完全相同的元素的列表.

I'm working inside a loop and I'd like to save plots in a list so I can plot them together in a .pdf. The problem is that the list is not filled up properly and re-updates with the results of the last run. So, in the end what I get is a list with five elements that are exactly the same.

我知道循环似乎没有用,但是我只是让它们创建一个尽可能接近真实代码的测试代码(带有可再现的错误).因此,我需要保持循环不变.

I'm aware the loops may seem useless, but I just have them to create a test code (with a reproducible error) as close to the real one as possible. So, I need to leave the loops as they are.

library (ggplot)
library (gridExtra)

plist <- list()

for (z in 1:5){
  n <- 100
  k <- seq(0, to=4500+z*2000, length=n)
  tmp <- numeric(n)
  for (i in 1:n){
    tmp[i] <- (5*(i*3)^2)}

  plist[[z]] <- ggplot() +
    geom_line(aes(x = k, y = tmp)) +
    theme_bw()

  pdf(sprintf("p%s.pdf", z),
      width = 6, height = 4, onefile = T)
  plot(plist[[z]])
  dev.off()
}

do.call(grid.arrange, c(plist, ncol = 5))

推荐答案

此答案基于:

这篇关于循环内时如何将图存储在列表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆