【问题标题】:Convert NetCDF to SpatialGridDataFrame with R使用 R 将 NetCDF 转换为 SpatialGridDataFrame
【发布时间】:2013-11-18 11:20:34
【问题描述】:

我尝试将 netCDF 文件转换为 SpatialGridDataFrame 类以绘制地图。 在我的 netCDF 文件中,我有坐标(经度/纬度)、时间(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)

【问题讨论】:

    标签: r converter netcdf


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2012-06-02
      • 2012-07-03
      • 2020-04-28
      • 2021-01-30
      • 1970-01-01
      • 2019-09-20
      • 2013-03-04
      • 2014-05-20
      相关资源
      最近更新 更多