带有面板图的地图

map with panel plots

我正在学习这个优秀的例子here。一切正常,直到网格绘制,

library("lattice")
spplot(sp_grd, "id", colorkey=FALSE,
       panel = function(...) {
         panel.gridplot(..., border="black", col.regions="white")
         sp.polygons(shp)
         sp.points(poi, cex=1.5)
         panel.text(..., col="red")
       })

当我尝试此绘图时,出现错误,

'使用数据包 1 时出错 形式参数 "col.regions" 与多个实际参数匹配'.

有什么修复的想法吗?基本上我不希望面板填充颜色,因为它默认这样做。

编辑:从 link 修改的可重现示例。

### read shapefile
library("rgdal")
library("lattice")
library("rworldmap")
shp <- getMap(resolution="low")

### define coordinates and convert to SpatialPointsDataFrame
poi <- data.frame(x=c(15, 25, 35, 100),
                  y=c(-15, 25, -35, -50),
                  id="A", stringsAsFactors=F)
coordinates(poi) <- ~ x + y
proj4string(poi) <- proj4string(shp)

### define SpatialGrid object
bb <- bbox(shp)
cs <- c(10, 10)
cc <- bb[, 1] + (cs/2)  # cell offset
cd <- ceiling(diff(t(bb))/cs)  # number of cells per direction
grd <- GridTopology(cellcentre.offset=cc, cellsize=cs, cells.dim=cd)

sp_grd <- SpatialGridDataFrame(grd,
                               data=data.frame(id=1:prod(cd)),
                               proj4string=CRS(proj4string(shp)))
# does work
spplot(sp_grd, "id",
       panel = function(...) {
         panel.gridplot(..., border="black")
         sp.polygons(shp)
         sp.points(poi, cex=1.5)
         panel.text(...)
       })

# does not work
spplot(sp_grd, "id",
       panel = function(...) {
         panel.gridplot(..., border="black", col.regions="white")
         sp.polygons(shp)
         sp.points(poi, cex=1.5)
         panel.text(...)
       })

您收到该错误消息是因为向 panel.gridplot() 传递了两个名为 col.regions 的不同参数。您已明确提供一个,另一个(默认情况下)通过面板函数的点 (...) 参数传递。

解决方案是将 col.regions 添加为面板函数的正式参数。这样,它将捕获来自外部(即来自 spplot())的 col.regions 参数,将其从被 ... 吸收的其他不匹配参数列表中删除。您对 panel.gridplot() 的调用将只有一个名为 col.regions= 的参数,并且会按您预期的那样工作。

这样做就可以了:

spplot(sp_grd, "id", colorkey=FALSE,
       panel = function(..., col.regions) {
         panel.gridplot(..., border="black", col.regions="white")
         sp.polygons(shp)
         sp.points(poi, cex=1.5)
         panel.text(...)
})