Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom placement of spplot legend in the map

Is it possible to place the spplot (spplot polygons) legend within the map, in lower left corner, like this?

enter image description here

The closest I've been able to get is this (I am not posting my data, I just use the example data instead, so in this case, try to place the legend in top left part of the map):

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

But the legend is in the middle of the page and is outside of the map. Unfortunatelly, colorkey argument doesn't support "bottomleft", or x, y, or corner arguments (see ?levelplot). I also tried to use key.space argument, but it seems to only work when plotting SpatialPoints* but it seems ignored for SpatialPolygons* (or SpatialPixelsDataFrame like in the example above).

like image 786
Tomas Avatar asked Mar 30 '15 11:03

Tomas


1 Answers

Since the key is a grob of its own it is perfectly possible to extract it from the plot object and draw it separately where ever you please.

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)

enter image description here

like image 63
Backlin Avatar answered Oct 11 '22 21:10

Backlin