2016-11-10 165 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