Munish Munish - 15 days ago 5
R Question

Overlaying world map on a image plot in R

I am trying to plot a global map using latitude, longitude and grid data in R. For this I am using image and image.plot functions. Additionally I need to overlay global coastline for land area. However I am not sure how to place the map exactly over my image of gridded data. Map is appearing bit shifted to the left in the console and that part is not visible either. See sample code below with random grid data.

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()

Answer

I found the answer after few attempts and a tip from colleague. What needs to be done is shift the longitude grid from 0:359 to -179.5:179.5 using following commands after grid_lon is declared:

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))
Comments