用R将NetCDF转换为SpatialGridDataFrame



我试图将netCDF文件转换为SpatialGridDataFrame类,以便绘制地图。在我的netCDF文件中,我有坐标(lon/lat)、时间(1431个值)和相对湿度值(777232个值,对应于532个点(lat/lon网格)和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)

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

相关内容

  • 没有找到相关文章

最新更新