2016-11-10 141 views
1

我想绘制使用R中的纬度,经度和网格数据的全球地图。为此,我使用image和image.plot函数。此外,我需要覆盖全球海岸线的土地面积。但是我不确定如何将地图完全放置在网格数据的图像上。地图出现在控制台左侧,并且该部分也不可见。请参阅下面的示例代码和随机网格数据。在R中的图像地图上覆盖世界地图

remove(list=ls()) 

library(fields) 

library(maps) 

grid_lon<-c(0.5:1:359.5) 

grid_lat<-c(-89.5:89.5) 

temp1<-matrix(data = rexp(200, rate = 10), nrow = 360, ncol = 180)#random matrix 

zlim=c(0,0.25) 

par(oma=c(3,0,0,0))# c(bottom, left, top, right)#plot margins 

image(grid_lon,grid_lat,temp1,axes=FALSE,xlab='',ylab='') 

map("world", fill=TRUE, col="white", bg="white", ylim=c(-90, 90),add=TRUE) 

title(main ='Main title') 
image.plot(zlim=zlim,legend.only=TRUE,horizontal=TRUE,legend.mar=0.4,legend.shrink=0.4,legend.width=0.4,nlevel=64,axis.args = list(cex.axis =1,at=zlim, labels=zlim,mgp=c(1, 0, 0),tck=0),smallplot=c(.25,.72, 0,.030), 
    legend.args=list(text=expression(textstyle(atop('anomaly', 
    paste('(meters)')),cex.main=1.2)),cex=1.2, side=1, line=1.6) 
    )#end image.plot 

box() 

回答

0

我在几次尝试和同事的小费后找到了答案。有什么需要做的是经度网格从0转变:359 -179.5:使用以下命令179.5 grid_lon声明后:

indexes_to_shift<-180 

grid_lon[grid_lon>=180]<-grid_lon[grid_lon>=180]-360 

grid_lon<-c(tail(grid_lon, indexes_to_shift), head(grid_lon, indexes_to_shift)) 
1

通常,使用贴图时,最好使用空间对象,为此可以定义投影方法。然后与地图的一致性得到更好的保证。由于您正在使用填充网格,因此明显的选择是使用包raster中的raster。然后您的代码会成为:

require (raster) 
require (maps) 
temp1<-matrix(data = rexp(180*360, rate = 10), nrow = 360, ncol = 180) #random matrix 
r<-raster(temp1,xmn=-179.5,xmx=179.5,ymn=-89.5,ymx=89.5,crs="+proj=longlat +datum=WGS84") 
plot(r) 
map("world",add=T,fill=TRUE, col="white", bg="white") 

EDIT

此代码不考虑该数据是作为一个360 * 180基体,而理想的是绘制(地图)180 * 360矩阵。转置是有风险的,因为它可能会导致颠倒的图像。为了确保正确的坐标与正确的值相关联,我们可以明确地将它们关联起来,然后转换为空间对象。执行此操作的for循环在下面的代码中很慢,也许它可以变得更高效,但它可以完成这项工作。

require (raster) 
require (maps) 
# basic data, as in code given 
grid_lon<-seq(0.5,359.5,1) 
grid_lat<-seq(-89.5,89.5,1) 
temp1<-matrix(data = rexp(200, rate = 10), nrow = 360, ncol = 180)#random matrix 
# transform into data frame, where coords are associated to values 
tt<-data.frame(lon=rep(NA,64800),lat=rep(NA,64800),z=rep(NA,64800)) 
ct<-0 
for (i in 1:360){ 
    for (j in 1:180){ 
    ct<-ct+1 
    tt$lon[ct]<-grid_lon[i] 
    tt$lat[ct]<-grid_lat[j] 
    tt$z[ct]<-temp1[i,j] 
    } 
} 
# transform to spatial structure 
coordinates(tt)<- ~lon+lat 
# make spatial structure gridded 
gridded(tt)<-TRUE 
# transform to raster 
r<-raster(tt) 
projection(r)<-crs("+proj=longlat +datum=WGS84") 
# plot 
plot(r) 
map("world2",add=T,fill=TRUE, col="white", bg="white") 
+0

你好彼得,我不能使用的光栅功能在这种情况下,原因是:我想要矩阵temp1使用来自grid_lat和grid_lon的坐标信息绘制全局数据; temp1是360 * 180(Long * Lat)全局网格,图像函数将读取参数并显示180 * 360网格,如Lat * Long。此外,在这种情况下,仅仅进行转置也无济于事,情节需要将坐标定位并绘制在正确的位置。 – Munish

+0

如果我理解的很好,可以从某个来源或例程中获取temp1作为360 * 180矩阵。我忽略了这一点。但为什么转置不起作用?即使它会产生一张颠倒的地图(我看不出为什么会这样),很容易恢复正确的方向。顺便提一下,地图包中有一个以太平洋为中心(180E)的地图,称为“地图2”,您可以将其绘制到图像上。 –

+0

感谢您的帮助彼得,我发布了一个解决方案,可以满足我的目的。 – Munish