我有一个光栅文件'airtemp‘和一个多边形形状文件’大陆‘。我想把‘大陆’叠加在'airtemp‘上,这样’大陆‘的边界就可以在'airtemp’上面看到了。我用levelplot (晶格)绘制光栅文件。我先是用readShapeSpatial (maptools)读取了多边形,然后是plot。
问题是levelplot和plot的规模不同。Plot往往具有较小的框架。对不起,我没有可重复的样本,但我觉得这是地球物理学家的一个相当普遍的问题。我在这里发现了一个类似的问题:
http://r.789695.n4.nabble.com/overlaying-a-levelplot-on-a-map-plot-td2019419.html
但我不太明白解决方案。
发布于 2013-08-21 19:35:08
您可以使用latticeExtra包(随rasterVis自动加载)中的+.trellis和layer函数覆盖shapefile。
library(raster)
library(rasterVis)让我们构建一些数据来玩吧。如果您已经有一个光栅文件和一个shapefile,则可以跳过此部分。
library(maps)
library(mapdata)
library(maptools)
## raster
myRaster <- raster(xmn=-100, xmx=100, ymn=-60, ymx=60)
myRaster <- init(myRaster, runif)
## polygon shapefile
ext <- as.vector(extent(myRaster))
boundaries <- map('worldHires', fill=TRUE,
xlim=ext[1:2], ylim=ext[3:4],
plot=FALSE)
## read the map2SpatialPolygons help page for details
IDs <- sapply(strsplit(boundaries$names, ":"), function(x) x[1])
bPols <- map2SpatialPolygons(boundaries, IDs=IDs,
proj4string=CRS(projection(myRaster)))现在,使用rasterVis::levelplot打印光栅文件,使用sp::sp.polygons打印shapefile,然后使用+.trellis和layer生成整体图形。
levelplot(myRaster) + layer(sp.polygons(bPols))

sp.polygons使用透明颜色作为fill的默认颜色,但您可以更改它:
levelplot(myRaster) + layer(sp.polygons(bPols, fill='white', alpha=0.3))

发布于 2013-07-12 15:03:41
根据this discussion,有一种方法可以做到这一点:它将SpatialPolygonsDataFrame分解成由NAs分隔的多边形坐标的单个矩阵。然后使用panel.polygon将其绘制在levelplot图上。
library(maptools)
a <- matrix(rnorm(360*180),nrow=360,ncol=180) #Some random data (=your airtemp)
b <- readShapeSpatial("110-m_land.shp") #I used here a world map from Natural Earth.这就是有趣的开始:
lb <- as(b, "SpatialPolygons")
llb <- slot(lb, "polygons")
B <- lapply(llb, slot, "Polygons") #At this point we have a list of SpatialPolygons
coords <- matrix(nrow=0, ncol=2)
for (i in seq_along(B)){
for (j in seq_along(B[[i]])) {
crds <- rbind(slot(B[[i]][[j]], "coords"), c(NA, NA)) #the NAs are used to separate the lines
coords <- rbind(coords, crds)
}
}
coords[,1] <- coords[,1]+180 # Because here your levelplot will be ranging from 0 to 360°
coords[,2] <- coords[,2]+90 # and 0 to 180° instead of -180 to 180 and -90 to 90然后就是绘图了:
levelplot(a, panel=function(...){
panel.levelplot(...)
panel.polygon(coords)})格子中的思想是在参数panel中定义绘图函数(有关此主题的完整解释,请参阅?xyplot )。itself图本身的函数是levelplot。

当然,在您的例子中,使用base图形绘制似乎更简单:
image(seq(-180,180,by=1),seq(-90,90,by=1),a)
plot(b, add=TRUE)

https://stackoverflow.com/questions/17582532
复制相似问题