使用 R 从 csv 生成 NetCDF

问题描述

我有一个 .csv 文件,其中包含大西洋的经纬度坐标。我将每个坐标与值 1 相关联。我的目标是生成此数据的 Netcdf 以绘制它。这是 .csv 文件的片段:

lat     lon    value
24.75  -97.25    1
24.25  -97.25    1
23.75  -97.25    1
23.25  -97.25    1
22.75  -97.25    1
22.25  -97.25    1
27.25  -96.75    1
26.75  -96.75    1
26.25  -96.75    1
25.75  -96.75    1
25.25  -96.75    1

我使用这段代码生成了 .csv 文件的 Netcdf 文件

# read in csv file
atlantic <- read.csv(file = 'atlantic.csv')

# define dimensions
xvals <- unique(atlantic$lon)
xvals <- xvals[order(xvals)]
yvals <- unique(atlantic$lat)
yvals <- yvals[order(yvals)]
lon1 <- ncdim_def("longitude","degrees_east",xvals)
lat2 <- ncdim_def("latitude","degrees_north",yvals)

# define variables
mv <- -999 # missing value to use
var_value <- ncvar_def("Atlantic","1",list(lon1,lat2),longname="Atlantic area",mv)

# add data
ncnew <- nc_create(filename = "atlantic.nc",list(var_value))

# create the indices for the dimensions
atlantic$idx_lon <- match(atlantic$lon,xvals)
atlantic$idx_lat <- match(atlantic$lat,yvals)

# create an array with the dimensions appropriate for the data
m <- array(mv,dim = c(length(yvals),length(xvals)))

# fill the array with the values
for(i in 1:NROW(atlantic)){
    m[atlantic$idx_lat[i],atlantic$idx_lon[i]] <- atlantic$value[i]
}

# write the data and close
ncvar_put(ncnew,var_value,m)
nc_close(ncnew)

但是,当我使用 Panoply 绘制 Netcdf 时,它看起来很奇怪。

Atlantic_map

为什么会有一堆水平线?我希望它是连续的。我在这里错过了什么?

.csv 数据文件链接atlantic

解决方法

水平条纹是原始数据被拉伸以填充其原始网格的结果。我通过将原始数据映射到一个 360 度 x 180 度的数组来解决这个问题,然后再绘制全套。