簡體   English   中英

R:在levelplot上的疊加圖

[英]R: overlay plot on levelplot

我有一個光柵文件'airtemp'和一個多邊形shapefile'大陸'。 我想把'大陸'疊加在'airtemp'上,所以'大陸'的邊界在'airtemp'的頂部可見。 我按levelplot (點陣)繪制光柵文件。 我首先通過readShapeSpatial (maptools)讀取多邊形,然后plot

問題是levelplotplot有不同的尺度。 Plot往往具有較小的框架。 對不起,我沒有可重復的樣本,但我覺得這對地球物理學家來說是一個相當普遍的問題。 我在這里發現了一個類似的問題:

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

但我不太明白解決方案。

您可以使用來自latticeExtra包(自動加載rasterVis )的+.trellislayer函數覆蓋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,並使用+.trellislayer生成整體圖形。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM