如何正确将NCDF文件导入为data.frame并避免数据错位
错误原因
- 维度不匹配:你从NetCDF中提取的气象变量(温度、降水等)都是三维数组(结构为
[经度, 纬度, 时间]),而long、lat是一维向量,直接用cbind拼接会完全破坏经纬度和气象值的对应关系,这是数据错位的核心原因。 - 单独去NA导致行不对应:你对每个气象变量单独执行
na.omit(),不同变量剔除NA的行数、位置都不一致,拼接后同一行的数据完全不对应同一个经纬度+时间的点位,数据整体全部混乱。 - 无效变量引用:ggplot代码中引用的
poging1.df在你的代码中没有定义,直接调用会进一步导致绘图错误。
修正方案
核心思路是先构造所有经纬度+时间的完整组合,再将三维气象变量拉平为一维向量和组合一一对应,全程不破坏原始的数组对应关系:
library(ncdf4) library(raster) library(ggplot2) weatherpress <- nc_open("C:/Users/heinj/OneDrive/Documenten/Universiteit/Master/Master Thesis/dataset/allecoors5augweer.nc") # 提取维度 long<- ncvar_get(weatherpress, "longitude") lat <- ncvar_get(weatherpress, "latitude") tijd <- ncvar_get(weatherpress, "time") # 提取变量,不要提前执行na.omit破坏结构 rain <- ncvar_get(weatherpress,"crwc") temperature <- ncvar_get(weatherpress, "t") Uwind <- ncvar_get(weatherpress, "u") Vwind <- ncvar_get(weatherpress, "v") # 替换填充值为NA fillvaluecrwc <- ncatt_get(weatherpress, "crwc", "_FillValue") rain[rain == fillvaluecrwc$value] <- NA fillvaluet <- ncatt_get(weatherpress, "t", "_FillValue") temperature[temperature == fillvaluet$value] <- NA fillvalueu <- ncatt_get(weatherpress, "u", "_FillValue") Uwind[Uwind == fillvalueu$value] <- NA fillvaluev <- ncatt_get(weatherpress, "v", "_FillValue") Vwind[Vwind == fillvaluev$value] <- NA nc_close(weatherpress) # 构造所有经纬度+时间的完整组合,保证点位一一对应 grid_df <- expand.grid(long = long, lat = lat, tijd = tijd) # 将三维变量拉平为一维向量,和grid_df的点位顺序完全匹配 grid_df$rain <- as.vector(rain) grid_df$temperature <- as.vector(temperature) grid_df$Uwind <- as.vector(Uwind) grid_df$Vwind <- as.vector(Vwind) # 统一去除含NA的行,保证所有变量对应同一个点位 weather <- na.omit(grid_df) # 单时间切片绘图测试 取第一个时间点 temp_slice <- subset(weather, tijd == tijd[1]) ggplot(temp_slice, aes(x = long, y = lat)) + geom_raster(aes(fill = temperature)) + coord_quickmap() # 栅格化测试 r <- raster(xmn = min(long), xmx=max(long), ymn=min(lat), ymx=max(lat), res = 10) cordi <- temp_slice[,c("long", "lat")] coordinates(cordi) <- ~long + lat temp_sp <- SpatialPointsDataFrame(cordi, temp_slice) meanr <- rasterize(temp_sp, r, "temperature", fun = mean) plot(meanr)
内容的提问来源于stack exchange,提问作者HeinB
相关产品推荐
相关产品推荐

