在地图中自定义spplot图例的位置

8

是否可以将spplot(spplot多边形)图例放在地图内部,位于左下角,就像这样?

enter image description here

我能做到的最接近的效果是这样的(我没有发布我的数据,我只是使用示例数据,因此在此情况下,请尝试将图例放置在地图的左上部分):

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

但是图例位于页面中央并且在地图的外部。不幸的是,colorkey参数不支持“bottomleft”,或者x、y或角落参数(请参阅?levelplot)。我还尝试使用key.space参数,但似乎仅在绘制SpatialPoints*时起作用,但对于SpatialPolygons*(或像上面示例中的SpatialPixelsDataFrame)似乎被忽略了。
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)

在这里输入图像描述


完全不用谢,很高兴你喜欢!不过这个方法有点取巧,因为它通过键的中心相对于绘图区域大小来定义位置,如果图形被重新缩放,它就会偏离原位。更好的解决方案是通过距离绘图区域边界的绝对距离来定义左上角的位置,但不幸的是我不知道如何实现。 - Backlin
谢谢Backlin!我想问你关于这个问题的确切位置 - 相对于左上角的定位。是否有像key.spacecorner参数一样的可能性? - Tomas
我在draw.colorkey()的代码中没有看到类似于corner参数的内容,因此我决定单独创建和绘制关键字。位置由key$framevp决定,它是一个gridviewport。我相信有一种适当的方法来定位它,但我仍然觉得它们很难理解和使用。 - Backlin
1
@Backlin -- 刚刚发布了一个解决方案,受到你的答案启发,它修复了颜色键在重新缩放图形时漂移的问题。它还通过通过spplot()"legend="参数传递参数和指令来避开视口参数的低级黑客攻击,从而调用draw.colorkey() - Josh O'Brien

7
这里的复杂问题在于,尽管colorkey=参数与legend=参数非常相似,但它并不完全支持与legend=相同的所有定位选项。而图例可以直接放置在绘图的左侧、右侧、顶部、底部和内部,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))

enter image description here

注意: colorkey=不支持“inside”选项似乎不是设计选择,而只是包作者尚未实现必要代码的问题。作为证据,请参见?lattice::levelplotcolorkey=的文档(其中一个被?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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接