[英]R: overlay plot on 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
但我不太明白解决方案。
您可以使用来自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))
根据这个讨论 ,这里有一种方法:它包括将SpatialPolygonsDataFrame分解为由NA分隔的一个多边形坐标矩阵。 然后使用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
。
当然,在您的情况下,使用base
图形绘制它似乎更简单:
image(seq(-180,180,by=1),seq(-90,90,by=1),a)
plot(b, add=TRUE)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.