1

I have extracted information from a large NetCDF file but have problems converting it into raster. In short I can plot the matrix fine with levelplot, however when I try to convert it into raster and plot it, the results look totally wrong and scattered. I should mention that I believe the original NetCDF is based on Cylindrical Equal Area projection with central meridian and parallel set to 0.

library(raster)
library(rasterVis)
library(maptools)
library(maps)
library(ncdf4)
library(ncdf.tools)
library(chron)
library(lattice)
library(RColorBrewer)

setwd("D:/...")


ncdf <- nc_open("2013FullYear.nc")

lon <- ncvar_get(ncdf,"Longitude")
nlon <- dim(lon)
head(lon)

lat <- ncvar_get(ncdf,"Latitude")
nlat <- dim(lat)
head(lat)

# Create a vector for Variable week
t <- ncvar_get(ncdf,"Step")
t

# Variable of interest in the NetCDF file
dname <- "Weekly Growth Index"

# Array with 
tmp_array <- ncvar_get(ncdf,dname)

m <- 1
tmp_slice <- tmp_array[,,m]

# Create list with matrices for each time slot
tmp_stack <- vector("list",length(t))

for (i in 1:length(t)) {
        tmp_stack[[i]] <- tmp_array[,,i]
}

# Create list for 4 seasons:
tmp_stack_1 <- vector("list",length(t)/4)
for (i in 1:13) {
        tmp_stack_1[[i]] <- tmp_array[,,i]
}

tmp_stack_2 <- vector("list",length(t)/4)
for (i in 14:26) {
        for (j in 1:13){
                tmp_stack_2[[j]] <- tmp_array[,,i]
        }

}

tmp_stack_3 <- vector("list",length(t)/4)
for (i in 27:39) {
        for (j in 1:13){
                tmp_stack_3[[j]] <- tmp_array[,,i]
        }

}

tmp_stack_4 <- vector("list",length(t)/4)
for (i in 40:52) {
        for (j in 1:13){
                tmp_stack_4[[j]] <- tmp_array[,,i]
        }

}

# Summarize the seasons:
tmps_stack_avg1 <- Reduce("+",tmp_stack_1)/length(tmp_stack_1)
tmps_stack_avg2 <- Reduce("+",tmp_stack_2)/length(tmp_stack_2)
tmps_stack_avg3 <- Reduce("+",tmp_stack_3)/length(tmp_stack_3)
tmps_stack_avg4 <- Reduce("+",tmp_stack_4)/length(tmp_stack_4)

tmps_stack_max1 <- apply(simplify2array(tmp_stack_1), 1:2, max)
tmps_stack_max2 <- apply(simplify2array(tmp_stack_2), 1:2, max)
tmps_stack_max3 <- apply(simplify2array(tmp_stack_3), 1:2, max)
tmps_stack_max4 <- apply(simplify2array(tmp_stack_4), 1:2, max)



# Piece of code that gives nice map that looks right:
grid <- expand.grid(lon=lon, lat=lat)
cutpts <- seq(0,1,0.1)
levelplot(tmps_stack_max1 ~ lon * lat, data=grid, at=cutpts, cuts=11, pretty=T, 
          col.regions=(rev(brewer.pal(10,"RdBu"))))

I need to convert my matrix to raster and then it gets strange:

# Convert to raster attempt 1 - gives strange result!
raster1 <- raster(
        tmps_stack_max1,
        xmn=min(lon),xmx=max(lon),
        ymn=min(lat),ymx=max(lat),
        #crs=CRS(+proj=longlat +datum=WGS84)
        crs=CRS("+proj=cea  +lat_0=0 +lon_0=0")
)

plot(raster1)

#### Convert to raster... again wrong output!
r <- raster(tmps_stack_max1, xmn=min(lon), xmx=max(lon), ymn=min(lat), ymx=max(lat)) 

s <- as(r, 'SpatialGridDataFrame') 
spplot(s)
writeGDAL(s, "SGDF.tif")
MIH
  • 1,083
  • 3
  • 14
  • 26
  • Have you tried using `raster` function to read in the `netcdf` file? `r <- raster("2013FullYear.nc", varname="Weekly Growth Index")` – Geo-sp Jan 24 '17 at 18:46
  • I get the following error: Error in .rasterObjectFromCDF(x, type = objecttype, band = band, ...) : cells are not equally spaced; you should extract values as points I should mention that I believe the projection of the NetCDF file is Cylindrical Equal-Area with central Meridian = 0. Would that affect it? – MIH Jan 24 '17 at 20:02
  • 1
    You cannot use raster for this without ensuring the extent is correct in the native crs, something NetCDF is not well used for. Can you share a file? – mdsumner Jan 24 '17 at 20:21
  • 1
    There is a hidden argument to raster() stopIfNotEqualSpaced that can be used to avoid the error, but then requires manual fix for the CRS/extent. – mdsumner Jan 24 '17 at 20:23
  • @mdsumner Ok, file is now here: warning it is ca.500MB, can crop it if needed tomorrow. Anyways thanks a lot for the insights! https://drive.google.com/open?id=0B7-8DA0HVZqDTVB1b3NYT25Tc1k – MIH Jan 24 '17 at 22:49
  • Is it compressed? . Happy to download either way, but. worth zipping at least if you haven't – mdsumner Jan 25 '17 at 10:37
  • @mdsumner I added compressed file in .zipx, it is now 227MB – MIH Jan 25 '17 at 10:45
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/133983/discussion-between-anna-and-mdsumner). – MIH Jan 25 '17 at 12:42
  • 1
    Was this issue resolved? The chat link doesn't work and I am experiencing the same issue – matlabcat Nov 29 '21 at 15:18

0 Answers0