How to save and name multiple plots with R

好久不见. 提交于 2019-12-25 01:46:25

问题


I have a list of 73 data sets generated by the function "mcsv_r()" called "L1" and a function "gc()" that generates a map. Using "lapply" I can create my 73 plots. I need to save and name all of them. I know I can do it one by one with RStudio. But I am sure that thanks to "jpeg()" and "dev.off" and mixing them with a loop I can do it with a few lines of code.

out <- setwd("C:/")
dir(out)
mcsv_r(dir(out))

gc <- function(x){
  xlim <- c(-13.08, 8.68)
  ylim <- c(34.87, 49.50)
  map("world", lwd=0.05, xlim=xlim, ylim=ylim)
  map.axes()
  symbols(x$lon, x$lat, bg="#e2373f", fg="#ffffff", lwd=0.5, circles=rep(1, length(x$lon)), inches=0.05, add=TRUE)
  node <- x[x$node == 1, c("lon", "lat")]
  for (i in 2:nrow(x)) lines(gcIntermediate(node, x[i, c("lon", "lat")]), col="red", lwd=0.8)
}


lapply(L1, gc)

Anyone can help me!? Thanks in advance. This is my code...


回答1:


As you can read in ?jpeg you can use a filename with a "C integer format" and jpeg will create a new file for each plot, e.g.:

jpeg(filename="Rplot%03d.jpeg")
plot(1:10)  # will become Rplot001.jpeg
plot(11:20) # will become Rplot002.jpeg
dev.off()

In your case the following should work:

jpeg(filename="Rplot%03d.jpeg")
lapply(L1, gc)
dev.off()



回答2:


The easiest way is to construct different filenames in each loop iteration, using paste() for the filename of jpeg().

for ( ii in 1:10 ) {
  jpeg(paste(ii,".jpg",sep=""))
    plot(rnorm(10),rnorm(10))
  dev.off()
}


来源:https://stackoverflow.com/questions/27081773/how-to-save-and-name-multiple-plots-with-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!