用正确的网格绘制R中的netcdf

时间:2014-03-10 13:18:50

标签: r plot ggplot2 maps netcdf

我的目标是使用正确的经度和纬度为世界地图绘制硝酸盐(no3)数据。

有两个netcdf文件:
1. with the data
2. with the grid information

有关数据的摘要信息:     no3是长度为x * y * sigma的数组     no3_df是'x * y obs。 3个变量'     x =整数[180]     y =整数[193]     sigma = array [53]

我想看看西格玛('深度')20。因此,我做了以下事情:

# Load the needed libraries to handle netcdf files
library(ncdf)
library(akima)

# Open data and grid files
file1 <- open.ncdf(file.choose())
grid  <- open.ncdf(file.choose())

# Read relevant variables/parameters from data file1
x <- get.var.ncdf(file1,varid="x")
y <- get.var.ncdf(file1,varid="y")
sigma <- get.var.ncdf(file1,varid="sigma")
no3 <- get.var.ncdf(file1,varid="no3")
sigma_plot <- no3[,,sigma=20]

# Read relevant variables/parameters from grid file
plon <- get.var.ncdf(grid,varid="plon")
plat <- get.var.ncdf(grid,varid="plat")

# Each cell of sigma_plot corresponds to one cell of plon and plat.
A <- array(c(plon,plat,sigma_plot),dim=c(180,193,3))

# Now B is an array containing for each row: (longitude, latitude, value).
B <- apply(A, 3, cbind)

# But it is not a regular grid, so interpolate to a regular grid. akima library
C <- interp(B[,1],B[,2],B[,3], 
            xo=seq(-180,180,1),yo=seq(-90,90,by=1), # tweak here the resolution
            duplicate='mean') # extra y values are duplicates

#########
# PLOTTING
#########

# This one works, but doesn't have a correct longitude and latitude:
filled.contour(x,y,sigma_plot, col=rich.colors(18))

# Try to plot with lon and lat
filled.contour(C, col=rich.colors(30))

由于fill.contour图没有正确的经度和纬度,我想使用ggplot。但是,我不知道该怎么做......

# And the plotting with ggplot
ggplot(aes(x=plon_datafrm,y=plat_datafrm),data=no3_df) +
  geom_raster() +
  coord_equal() +
  scale_fill_gradient()

这似乎不起作用。我是ggplot的网,所以这可能是原因,我真的很感激任何帮助。

1 个答案:

答案 0 :(得分:2)

library(ncdf)
data <- open.ncdf(file1)
no3 <- get.var.ncdf(data,varid="no3")
sigma_plot <- no3[,,20]
grid <- open.ncdf(file2)
plon <- get.var.ncdf(grid,varid="plon")
plat <- get.var.ncdf(grid,varid="plat")

与我之前所理解的相反,sigma_plot的每个单元格对应于plon和plat的一个单元格。

A <- array(c(plon,plat,a),dim=c(180,193,3))
B <- apply(A, 3, cbind)

现在B是一个包含每一行的数组:(经度,纬度,值)。但它不是常规网格,因此您需要插入常规网格。最简单的方法是使用包interp中的akima

library(akima)
C <- interp(B[,1],B[,2],B[,3], 
            xo=seq(-180,180,1),yo=seq(-90,90,by=1), #you can tweak here the resolution
            duplicate='mean') #for some reasons some entries are duplicates, i don t know how you want to handle it.

image(C) #for instance, or filled.contour if you prefer
library(maptools)
data(wrld_simpl)
plot(wrld_simpl, add=TRUE, col="white") #To add a simple world map on top