如何在R中保存使用循环和mapplot程序包构建的多个图形?

问题描述

set.seed(1000);DF=data.frame(Lon=runif(20,-93,-87),Lat=runif(20,27,30),Pie1=sample(50,20),Pie2=sample(50,Pie3=sample(50,20));head(DF);NGoM<-getNOAA.bathy(-93,-87,28,31,resolution=1,keep=FALSE)
for(i in colnames(DF[,3:5])){
z=DF[,i]
dev.new()
plot(NGoM,col=brewer.pal(n=6,name="Blues"),bg="blue",xaxt="n",yaxt="n",xlab="",ylab="")
map(add=TRUE,col="gray",fill = TRUE)
compassRose(-92,30.5,rot=0,cex=1)
scalebar(200,xy= c(-90,19.4),type = "bar",divs = 4,cex = 0.7,below = "kilometers",lwd=2,family="Arial")
Ad<-aggregate(list(z=z),list(x=DF$Lon,y=DF$Lat),sum)
draw.bubble(Ad$x,Ad$y,Ad$z,maxradius= 0.25,pch=21,bg=("red"))
legend.bubble(x=-90,y=30.8,z=max(Ad$z),maxradius=0.25,bg="gray78",txt.cex=0.8,pt.bg="red")
text(St$Lon,St$Lat,St$Station,family="Arial",cex=0.8,pos=1)
mtext(text="Longitude",side=1,line=2,cex=1)
mtext(text="Latitude",side=2,line=4,cex=1)
degAxis(1,cex.axis=1)
degAxis(2,las=1,cex.axis=1)
Box()
ggsave(filename = paste0("C:/Users/xxx/Documents/fig_",i,.tiff"),plot =last_plot(),device = "png",dpi = 600)

上面提供的代码获取多个地图图的示例;但是,保存的文件为空。

解决方法

在不同网站上查找有关r功能的信息后,我找到了解决问题的方法。

第一步是在循环的第一部分设置图形选项

png(paste0("Amap",i,".tiff"),width = 1024,height = 768)

第二步也是最后一步是关闭box()之后的函数。

dev.off()