R:在levelplot上的叠加图

EDU*_*EDU 4 plot r levelplot

我有一个光栅文件'airtemp'和一个多边形shapefile'大陆'.我想把'大陆'叠加在'airtemp'上,所以'大陆'的边界在'airtemp'的顶部可见.我用levelplot(晶格)绘制光栅文件.我readShapeSpatial首先通过(maptools)读取多边形然后plot.

问题是levelplot并且plot有不同的规模.Plot往往有较小的框架.对不起,我没有可重复的样本,但我觉得这对地球物理学家来说是一个相当普遍的问题.我在这里发现了一个类似的问题:

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

但我不太明白解决方案.

Osc*_*ñán 11

您可以使用包中的+.trellislayer 函数latticeExtra(自动加载rasterVis)覆盖shapefile .

library(raster)
library(rasterVis)
Run Code Online (Sandbox Code Playgroud)

让我们构建一些数据.如果您已有光栅文件和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)))
Run Code Online (Sandbox Code Playgroud)

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

levelplot(myRaster) + layer(sp.polygons(bPols))
Run Code Online (Sandbox Code Playgroud)

覆盖透明色

sp.polygons使用透明颜色作为默认颜色fill,但您可以更改它:

levelplot(myRaster) + layer(sp.polygons(bPols, fill='white', alpha=0.3))
Run Code Online (Sandbox Code Playgroud)

覆盖白色


pla*_*pus 1

根据此讨论,这是执行此操作的一种方法:它将 SpatialPolygonsDataFrame 分解为一个由 NA 分隔的多边形坐标矩阵。然后使用将其绘制在水平图上panel.polygon

\n\n
library(maptools)\na <- matrix(rnorm(360*180),nrow=360,ncol=180) #Some random data (=your airtemp)\nb <- readShapeSpatial("110-m_land.shp") #I used here a world map from Natural Earth.\n
Run Code Online (Sandbox Code Playgroud)\n\n

这就是乐趣的开始:

\n\n
lb <- as(b, "SpatialPolygons")\nllb <- slot(lb, "polygons")\nB <- lapply(llb, slot, "Polygons") #At this point we have a list of SpatialPolygons\ncoords <- matrix(nrow=0, ncol=2)\nfor (i in seq_along(B)){\n    for (j in seq_along(B[[i]])) {\n        crds <- rbind(slot(B[[i]][[j]], "coords"), c(NA, NA)) #the NAs are used to separate the lines\n        coords <- rbind(coords, crds)\n        }\n    }\ncoords[,1] <- coords[,1]+180 # Because here your levelplot will be ranging from 0 to 360\xc2\xb0\ncoords[,2] <- coords[,2]+90 # and 0 to 180\xc2\xb0 instead of -180 to 180 and -90 to 90\n
Run Code Online (Sandbox Code Playgroud)\n\n

然后是情节:

\n\n
levelplot(a, panel=function(...){\n                        panel.levelplot(...)\n                        panel.polygon(coords)})\n
Run Code Online (Sandbox Code Playgroud)\n\n

lattice 中的想法是定义参数中的绘图函数panel?xyplot有关该主题的完整解释请参阅 参考资料)。levelplot 本身的函数是levelplot

\n\n

在此输入图像描述

\n\n

当然,就您而言,使用base图形绘制它似乎更简单:

\n\n
image(seq(-180,180,by=1),seq(-90,90,by=1),a)\nplot(b, add=TRUE)\n
Run Code Online (Sandbox Code Playgroud)\n\n

在此输入图像描述

\n