用R将NetCDF转换为SpatialGridDataFrame

时间:2013-11-18 11:20:35

标签: r converter netcdf

我尝试将netCDF文件转换为SpatialGridDataFrame类以绘制地图。 在我的netCDF文件中,我有坐标(lon / lat),时间(1431值)和相对湿度值(777232值对应532点(纬度/经度网格)和1431点(代表4个度量)一年中的一天))。我想绘制一个地图,即532点网格上的相对湿度值。

我真的不知道SpatialGridDataFrame或SpatialPixelsDaraFrame之间的区别,我试图用两个函数获得结果。这是我的代码:

library(ncdf)
library(maptools)

setwd("~/Documents/Data")


#Lire les données du ncdf, dans le cas d'une seule variable et 3 dimensions - Read data
nc <- open.ncdf("X195.221.112.194.318.6.28.31.nc")
lat <- get.var.ncdf(nc,"lat")
long <- get.var.ncdf(nc,"lon")
time <- get.var.ncdf(nc,"time")
data <- get.var.ncdf(nc)


#Redimensionner les données dans le bon format - To have good dimensions
lonlat <- SpatialPoints(expand.grid(long,lat), proj4string=CRS(as.character(NA)))
data <- as.data.frame(matrix(data,ncol=1461))

#Pas de temps pour lequel on veut tracer la carte - select time for the map
i=1461

#Changer la classe de l'objet de NetCDF vers SP - convert to SP
Grid <- SpatialPixelsDataFrame(lonlat,data[[i]], tolerance = sqrt(.Machine$double.eps))

这就是我得到的错误:

invalid class “SpatialPixelsDataFrame” object: invalid object for slot "data" in class "SpatialPixelsDataFrame": got class "numeric", should be or extend class "data.frame"
Warning:
In points2grid(points, tolerance, round) :
  grid has empty column/rows in dimension 1

有想法提供帮助吗?

答案之后:

library(ncdf)
library(maps)
library(fields)
library(scales)

setwd("~/Documents/Data")


nc <- open.ncdf("X195.221.112.194.322.0.48.19.nc")
lat <- get.var.ncdf(nc,"lat")
long <- get.var.ncdf(nc,"lon")
time <- get.var.ncdf(nc,"time")
var <- get.var.ncdf(nc, "hgt")
close.ncdf(nc)

i=100
nom_var="Hgt"
var.slice <- var[,,i]

nlevel=64   #number of colors
image.plot(seq(from=-20, to=30, by=2),seq(from=28, to=60, by=2),var.slice, 
           xlab = "Longitude", ylab = "Latitude", legend.shrink = 0.9, 
           legend.width = 1.2, legend.mar = NULL, main =nom_var,
           graphics.reset = FALSE, horizontal = FALSE, bigplot = NULL
           , smallplot = NULL, legend.only = FALSE, col = tim.colors(nlevel),
           lab.breaks=NULL, axis.args=NULL)


map(add=TRUE, fill=TRUE, col = alpha("grey", 0.5))
abline(v=seq(-21, 31, 2), lty=2)
abline(h=seq(27, 61, 2), lty=2)

1 个答案:

答案 0 :(得分:1)

我从未使用过这些功能,但这样做似乎很严格。 Raster包提供了一些强大的工具来重塑数据。当我使用ncdf文件工作(一些)时,我直接转到image()image.plot{fields}来绘制地图。使用image.plot(),您可以给出与行和列相对应的x和y值,以获得良好的轴刻度标签。我认为它本身适用expand.grid。一旦好的方法,您就可以轻松地从maps包的工具中受益。