[英]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.