8

是否可以像这样将 spplot(spplot 多边形)图例放置在地图的左下角?

在此处输入图像描述

我能得到的最接近的是这个(我没有发布我的数据,我只是使用示例数据,所以在这种情况下,尝试将图例放在地图的左上角):

data(meuse.grid)
gridded(meuse.grid)=~x+y
spplot(meuse.grid[,'dist'],
    colorkey = list(space = "left", height = 0.5)
)

但是图例在页面中间,在地图之外。不幸的是,colorkeyargument 不支持“bottomleft”、x、y 或角参数(请参阅 参考资料?levelplot)。我也尝试使用key.space参数,但它似乎只在绘图时有效,SpatialPoints*但它似乎被忽略了 SpatialPolygons*(或上面示例中的 SpatialPixelsDataFrame)。

4

2 回答 2

10

由于密钥是它自己的一个 grob,因此完全可以从绘图对象中提取它并在您喜欢的任何地方单独绘制它。

library(grid)

#  Separate plot and key
s <- spplot(meuse.grid[,'dist'],
    colorkey = list(space = "left", height = 0.5)
)
key <- draw.colorkey(s$legend[[1]]$args$key)
s$legend <- NULL # Otherwise we'd get two keys

# Modify key
key$framevp$x <- unit(0.15, "npc")
key$framevp$y <- unit(0.68, "npc")

# Plot
s
grid.draw(key)

在此处输入图像描述

于 2015-03-30T12:59:50.363 回答
7

这里复杂的问题是,尽管colorkey=参数被视为非常像legend=参数,但它并不完全支持完整的定位选项套件legend=。而图例可以直接放在"left", "right", "top", "bottom", 和"inside"情节,colorkey=只支持前四个。

一个相当干净的解决方法是提取由一次调用准备的 colorkey 参数列表,并通过其参数将其spplot()传递给第二次调用。“知道”如何准备一个 colorkey 对象,并且知道如何在绘图内绘制任意对象,因此我们可以将两者结合起来得到我们想要的:spplot()legend=colorkey=legend=

library(sp)
library(grid)
library(lattice)
data(meuse.grid)
gridded(meuse.grid)=~x+y

## Call spplot() once as a way to construct a list of arguments
## to draw.color.key
SP <- spplot(meuse.grid[,'dist'],
    colorkey = list(space = "left", height = 0.4)
)
args <- SP$legend$left$args$key

## Prepare list of arguments needed by `legend=` argument (as described in ?xyplot)
legendArgs <- list(fun = draw.colorkey,
                   args = list(key = args),
                   corner = c(0.05,.75))

## Call spplot() again, this time passing in to legend the arguments
## needed to print a color key
spplot(meuse.grid[,'dist'], colorkey = FALSE,
       legend = list(inside = legendArgs))

在此处输入图像描述

注意: colorkey=缺乏对“内部”选项的支持似乎不是设计选择,而不仅仅是包作者尚未开始实施必要代码的问题。作为证据,请参阅 colorkey=in的文档?lattice::levelplot(由 `?sp::spplot 指向的文档):

colorkey: logical specifying whether a color key is to be drawn
          alongside the plot, or a list describing the color key. The
          list may contain the following components:

          ‘space’: location of the colorkey, can be one of ‘"left"’,
              ‘"right"’, ‘"top"’ and ‘"bottom"’.  Defaults to
              ‘"right"’.

          ‘x’, ‘y’: location, currently unused

          ‘corner’: Interacts with x, y; currently unimplemented
于 2015-04-03T07:08:09.340 回答