【问题标题】:plot contour in different panels of sp plot在 sp 图的不同面板中绘制轮廓
【发布时间】:2018-07-27 16:35:40
【问题描述】:

我在堆栈中有 3 个不同的栅格。我需要绘制一个面板图并在每个面板上添加不同的 shapefile。到目前为止,我设法做到了以下几点;

    ## read the libraries
    library(raster)
    library(rgdal)
    library(sp)
    library(rworldmap)
    library(OceanView)

    ##random raster object
    r <- raster(ncol=40, nrow=20)
    r[] <- rnorm(n=ncell(r))
    # Create a RasterStack object with 3 layers
    s <- stack(x=c(r, r*2, r**2))

    ##coordinate system
    wgs<-CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs")


    ##reading the additional shape files
    w <- spTransform(getMap(), wgs)
    poly <- list(list("sp.lines", as(w, 'SpatialLines'), lwd = 
            0.5,col="black"))

    ##plotting with spplot
    plot(spplot(s,layout=c(3,1),sp.layout=poly,
                 colorkey =list(space = "right"),
                names.attr = c("a","b","c")))

到目前为止,我绘制了 3 个栅格,上面覆盖了一个 shapefile。现在我需要在面板图上分别绘制 3 个不同的轮廓。并且还需要在每个图上绘制风速箭头。我知道要做到这一点,我需要使用 contour() 和 quiver() 函数。但是,我无法绘制这些。

    ## different raster stack for the contour plot
    s1 <- stack(x=c(r/2, r*10, r**5))


    ##differnt wind components
    lat= matrix(rep(seq(-90,90,length.out=20),each=20), ncol=20, byrow=TRUE)
    lon=matrix(rep(seq(-180,180,length.out=20),each=20), ncol=20, byrow=F)
    u=matrix(rep(sample(seq(-2,2,length.out=1000),20),each=20), ncol=20, byrow=TRUE)
    v=matrix(rep(sample(seq(-2,2,length.out=1000),20),each=20), ncol=20, byrow=TRUE)

    ##plot the arrows
    quiver2D(u = u,v=v,x = lon, y = lat,add=T,type="simple")

谁能帮我解决这个问题?任何帮助将不胜感激。

【问题讨论】:

  • 我不清楚“面板图”应该是什么,也无法在任何这些包中找到函数quiver(或quiver2D)。
  • @42- 哦,对不起,我没有把所有的库都放在那里。通过面板图我的意思是说一个有 3 列和 1 行的图。我不想单独绘制每个栅格,而是想将它们组合在一个图中,并且 spplot 具有此 layout=c(3,1) 的功能。关于箭头图,有不同的包,如 pracma::quiver 或 OceanView::quiver2D 做同样的工作。
  • 所以您希望在单个输出页面上绘制多个图,或许以“横向”格式呈现?我现在从quiver2D 调用的checkinput 函数中得到一个错误。说'x' not compatible with u or v,可能是因为你设置set.seed()后没有测试你的随机值?
  • 我已经尝试了几次,但仍然无法让第二个块中的代码正常运行。
  • @42- 错误是由于行和列不匹配。我纠正了它,它现在应该可以工作了。如果你能在没有错误的情况下绘图,你能告诉我吗?

标签: r raster contour lattice sp


【解决方案1】:

首先,您需要确定调用了 lattice 范式中的哪个函数。这需要查看 ?spplot 帮助页面(我愚蠢地没有先这样做),或者沿着调用树跟踪类和函数(这是我实际所做的)。然后查看最终函数的帮助页面,看看有没有可以传入的参数来添加等高线:

showMethods("spplot",class="Raster", includeDefs=TRUE) # last argument need to see code
Function: spplot (package sp)
obj="Raster"
function (obj, ...) 
{
    .local <- function (obj, ..., maxpixels = 50000, as.table = TRUE, 
        zlim) 
    {
        obj <- sampleRegular(obj, maxpixels, asRaster = TRUE, 
            useGDAL = TRUE)
        if (!missing(zlim)) {
            if (length(zlim) != 2) {
                warning("zlim should be a vector of two elements")
            }
            if (length(zlim) >= 2) {
                obj[obj < zlim[1] | obj > zlim[2]] <- NA
            }
        }
        obj <- as(obj, "SpatialGridDataFrame")
        spplot(obj, ..., as.table = as.table)
    }
    .local(obj, ...)
}

> showMethods("spplot",class="SpatialGridDataFrame",includeDefs=TRUE)
Function: spplot (package sp)
obj="SpatialGridDataFrame"
function (obj, ...) 
spplot.grid(as(obj, "SpatialPixelsDataFrame"), ...)

> showMethods("spplot.grid",class="SpatialPixelsDataFrame",includeDefs=TRUE)

Function "spplot.grid":
 <not an S4 generic function>
> spplot.grid
Error: object 'spplot.grid' not found
> getAnywhere(spplot.grid)
A single object matching ‘spplot.grid’ was found
It was found in the following places
  namespace:sp
with value

function (obj, zcol = names(obj), ..., names.attr, scales = list(draw = FALSE), 
    xlab = NULL, ylab = NULL, aspect = mapasp(obj, xlim, ylim), 
    panel = panel.gridplot, sp.layout = NULL, formula, xlim = bbox(obj)[1, 
        ], ylim = bbox(obj)[2, ], checkEmptyRC = TRUE, col.regions = get_col_regions()) 
{
    if (is.null(zcol)) 
        stop("no names method for object")
    if (checkEmptyRC) 
        sdf = addNAemptyRowsCols(obj)
    else sdf = as(obj, "SpatialPointsDataFrame")
    if (missing(formula)) 
        formula = getFormulaLevelplot(sdf, zcol)
    if (length(zcol) > 1) {
        sdf = spmap.to.lev(sdf, zcol = zcol, names.attr = names.attr)
        zcol2 = "z"
    }
    else zcol2 = zcol
    if (exists("panel.levelplot.raster")) {
        opan <- lattice.options("panel.levelplot")[[1]]
        lattice.options(panel.levelplot = "panel.levelplot.raster")
    }
    scales = longlat.scales(obj, scales, xlim, ylim)
    args = append(list(formula, data = as(sdf, "data.frame"), 
        aspect = aspect, panel = panel, xlab = xlab, ylab = ylab, 
        scales = scales, sp.layout = sp.layout, xlim = xlim, 
        ylim = ylim, col.regions = col.regions), list(...))
    if (all(unlist(lapply(obj@data[zcol], is.factor)))) {
        args$data[[zcol2]] = as.numeric(args$data[[zcol2]])
        if (is.null(args$colorkey) || (is.logical(args$colorkey) && 
            args$colorkey) || (is.list(args$colorkey) && is.null(args$colorkey$at) && 
            is.null(args$colorkey$labels))) {
            if (!is.list(args$colorkey)) 
                args$colorkey = list()
            ck = args$colorkey
            args$colorkey = NULL
            args = append(args, colorkey.factor(obj[[zcol[1]]], 
                ck))
        }
        else args = append(args, colorkey.factor(obj[[zcol[1]]], 
            ck, FALSE))
    }
    ret = do.call(levelplot, args)
    if (exists("panel.levelplot.raster")) 
        lattice.options(panel.levelplot = opan)
    ret
}
<bytecode: 0x7fae5e6b7878>
<environment: namespace:sp>

您可以看到它支持通过, list(...)) 传递的附加参数。因此,使用contour=TRUE 将等高线添加到levelplot 是相当容易的,尽管它只出现在Arguments 列表中,而不出现在levelplot 的Usage 部分的命名参数中。尽管如此,在?levelplot 页面上的示例中测试表明它成功了。您的示例不是一个特别好的示例,因为它是如此细粒度并且没有上升或下降级别的模式。尽管如此,将contour=TRUE, 添加到spplot 的参数中确实会产生黑色轮廓线。 (时间戳是由于我的 Rprofile 设置中的格代码,因此不会显示在您的设备上)。

 png(); plot(spplot(s,layout=c(3,1),sp.layout=poly, contour=TRUE,
                  colorkey =list(space = "right"),
                 names.attr = c("a","b","c"))) ; dev.off()

如果有人开始破解 spplot.gridsp::panel.gridplot,那么 levelplot 的作者提供的以下材料可能会有用: https://markmail.org/search/?q=list%3Aorg.r-project.r-help+lattice+add+contours+to+levelplot#query:list%3Aorg.r-project.r-help%20lattice%20add%20contours%20to%20levelplot%20from%3A%22Deepayan%20Sarkar%22+page:1+mid:w7q4l7dh6op2lfmt+state:results

【讨论】:

  • @ 42- 感谢您的回答。我了解您正试图帮助我查看是否可以将附加参数传递给函数。但是,当您要绘制栅格 s 并从栅格 s 叠加等高线时,上述函数 'contour=TRUE' 有效。但是,我想绘制栅格 s 但覆盖另一个栅格 s1 的轮廓。我希望你能明白我的意思。
  • 格子函数可以让你专注于现有的面板,然后添加到现有的面板中。我实际上并没有看到您提供了一个说明您需要什么的示例。我认为您应该从一个简单栅格的简单图开始
  • @ 42- 我同意你的看法。由于我创建了一个具有随机值的栅格,因此等高线没有意义。我可以不采用随机栅格,而是采用火山数据集并将其绘制为datasets::volcano r= raster(volcano) extent(r)&lt;-c(-180,180,-90,90) plot(s[[1]]) contour(r,add=T,lwd=0.2,col="red") plot(w,add=T,lwd=0.2) quiver2D(u = u,v=v,x = lon, y = lat,by=2,scale=0.01,add=T,type="simple") 这是绘制数据的基本方法。我希望 spplot 做同样的工作,但也适用于其他栅格。
猜你喜欢
  • 2019-06-29
  • 2019-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-03
  • 1970-01-01
  • 2023-03-20
  • 2021-09-07
相关资源
最近更新 更多