简体   繁体   English

R:无法将绘图从循环输出到文件

[英]R: Cannot Output Plots To Files From A Loop

I am trying to output a series of the file using the R. 我正在尝试使用R输出一系列文件。

Usually, we can use the following code to output a plot: 通常,我们可以使用以下代码输出绘图:

jpeg("XXXXX_XXXX.jpg")

ggplot(data=YEAR_ZIP_DATA, aes(x=SOME_VARIABLE)) + geom_bar()

dev.off()

The above code can get me a file in the current working directory called XXXXX_XXXX.jpg 上面的代码可以给我一个当前工作目录中的文件XXXXX_XXXX.jpg

Now I want to write a loop to create a series of file: for each year, draw a bar chart for each zip code and save to the current directory. 现在,我想编写一个循环来创建一系列文件:每年,为每个邮政编码绘制一个条形图,然后保存到当前目录。 Here is the code: 这是代码:

# year_list: a list of distinctive years
for(year in year_list){
  # zip_list: a list of distinctive zip codes
  for(zip in zip_list){
    # some code to get a filename like 10010_2018.jpg
    filename <- (some code)

    # some code to subset the data to get the current zip and year
    year_zip_data <- (some code)

    jpeg(filename)

    ggplot(data=year_zip_data, aes(x=SOME_VARIABLE)) + geom_bar()

    dev.off()
  }
}

However, after the above loop, there is nothing in the current working directory... How should I solve the problem? 但是,在上述循环之后,当前工作目录中没有任何内容...我该如何解决该问题?

Thanks in advance! 提前致谢!

Try ggsave function. 尝试ggsave函数。 It directly saves the graphics object created by ggplot. 它直接保存由ggplot创建的图形对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM