如何在R中对SpatialPixelsDataFrame类对象进行多重绘制?

时间:2018-08-09 22:47:07

标签: r geospatial spatial raster levelplot

我有一个类似one provided in a StackOverflow response的代码,使用了Ege Rubak的答案,但是我一年中都在进行分析,所以我有特定年份每个月的图像。

enter image description here

library(gstat)
library(sp)

lat <-  c(-23.49174, -23.49179, -23.49182, -23.49183, -23.49185, -23.49187)
long <- c(152.0718, 152.0718, 152.0717, 152.0717, 152.0717, 152.0717)
pH <- c(8.222411, 8.19931, 8.140428, 8.100752, 8.068141, 8.048852)
sample <- data.frame(lat, long, pH)

x.range <- range(sample$long)
y.range <- range(sample$lat)

x<-seq(x.range[1], x.range[2], length.out=20)
y<-seq(y.range[1], y.range[2], length.out=20)
grd<-expand.grid(x,y)

coordinates(sample) = ~long+lat
coordinates(grd) <- ~ Var1+Var2
gridded(grd) <- TRUE

proj4string(sample) <- CRS("+proj=longlat +datum=WGS84")
proj4string(grd) <- CRS("+proj=longlat +datum=WGS84")

dat.idw <- idw(formula=pH ~ 1, locations = sample, newdata = grd, idp = 2.0)
#> [inverse distance weighted interpolation]

plot(dat.idw, axes = T)

如下图所示,我如何将这12张图像合并为一个绘图,并执行类似于ggplot刻面换行的操作?

enter image description here

测试this answer中建议的代码:

library(gridExtra)
library(raster)
s <- stack(raster(dat.idw))
s2 <- stack(raster(dat.idw))

p1 <- levelplot(s)
p2 <- levelplot(s2)
grid.arrange(p1, p2, ncol=2)

# Error in UseMethod("levelplot") : 
#  no applicable method for 'levelplot' applied to an object of class 
# "c('RasterStack', 'Raster', 'RasterStackBrick', 'BasicRaster')"

1 个答案:

答案 0 :(得分:1)

您可以通过准备栅格堆栈对象并将其提供给函数来使用levelplot包中的rasterVis函数。

library(raster)
library(rasterVis)

r1 <- raster(dat.idw)
r2 <- raster(dat.idw)

# I am only using two rasters as an example
# You can stack 12 rasters for your raster stack 
s <- stack(list(r1, r2))

rasterVis::levelplot(s)

enter image description here

或使用spplot包中的sp

sp::spplot(s)

enter image description here

tmap包。

图书馆(tmap)

tm_shape(s) +
  tm_raster()

enter image description here