2013-07-10 260 views
4

我有一个光栅文件'airtemp'和一个多边形shapefile'c​​ontinents'。我想在'airtemp'上叠加'continents',所以'continents'的边界在'airtemp'的顶部可见。我通过levelplot(格子)绘制光栅文件。我先读readShapeSpatial(maptools)多边形然后plotR:覆盖图上的覆盖图

问题是levelplotplot有不同的比例。 Plot往往有较小的框架。对不起,我没有可复制的样本,但我觉得这对地球物理学家来说是一个相当普遍的问题。我发现一个类似的问题在这里:

http://r.789695.n4.nabble.com/overlaying-a-levelplot-on-a-map-plot-td2019419.html

,但我不太明白的解决方案。

+1

回答说,那'levelplot'是晶格功能,'plot'是基础的,很难混合基础和网格图形。 – agstudy

回答

1

根据this discussion,这里有一种方法:它将SpatialPolygonsDataFrame分解为一个由NAs分隔的多边形坐标矩阵。然后使用panel.polygon将其绘制在水平面上。

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关于这个问题的完整解释)。 levelplot本身的函数是levelplot

enter image description here

当然,你的情况,似乎这样更简单的绘制该使用base显卡:

image(seq(-180,180,by=1),seq(-90,90,by=1),a) 
plot(b, add=TRUE) 

enter image description here

9

可以使用覆盖shape文件的+.trellislayer 功能来自latticeExtra包(这是自动 加载rasterVis)。

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))) 

现在你sp::sp.polygons绘制光栅文件与rasterVis::levelplot的 shape文件,整体图形制作 与+.trellislayer

levelplot(myRaster) + layer(sp.polygons(bPols)) 

overlay with transparent color

sp.polygons采用了透明色为默认fill,但你可以改变它:

levelplot(myRaster) + layer(sp.polygons(bPols, fill='white', alpha=0.3)) 

overlay with white color

+0

对这个例子使用包tidyverse可能会为'map'和'layer'产生冲突。如果你得到错误:试图创建没有几何图层,使用'latticeExtra :: layer'。 – Matifou