Dear Brandon and Wei,
I don't know the answer to your question but a somewhat similar solution
is when you plot a separate legend using lattice::draw.key() and disable
sp::spplot()'s built-in legend using argument "auto.key = FALSE".
An example:
# loading libraries
library(lattice)
library(sp)
library(gridExtra)
library(grid)
# drawing legend
no_of_categories <- 10
cutpoints <- seq(from = 0 - 0.0001, to = 1 + 0.0001, length.out =
no_of_categories + 1)
legend_text <- apply(X = cbind(round(cutpoints [1:no_of_categories], 1),
round(cutpoints [2:(no_of_categories + 1)], 1)), MARGIN = 1, FUN =
function(number) {return(paste(format(x = number, digits = 2), collapse
= " - "))})
legend_colors <- colorRampPalette(c("red", "orange", "yellow",
"lightgreen", "darkgreen"))(no_of_categories)
legend <- draw.key(key = list(reverse.rows = TRUE, space = "right",
rectangles = list(col = legend_colors, border = FALSE), text =
list(legend_text)), draw = FALSE)
dev.off()
# drawing maps
maps <- list()
for (column_name in colnames(sp_object at data)) {
map <- spplot(obj = sp_object, zcol = column_name, auto.key =
FALSE, col.regions = legend_colors, cuts = cutpoints)
maps <- append(maps , list(map))
}
maps <- append(maps , list(legend))
# plotting the map-legend composite to a png file
layout <- rbind(c(1,2), c(3,4), c(5,6)) # let's say we have 5 maps and a
legend
composite <- do.call(arrangeGrob, c(maps, list(layout_matrix = layout),
list(widths = c(1, 1))))
png(width = 1000, height = 1000, filename = "map.png"))
grid.newpage()
grid.draw(composite)
dev.off()
Hope this helps,
?kos Bede-Fazekas
Hungarian Academy of Sciences
2017.08.06. 11:53 keltez?ssel, Brandon Payne ?rta:
How to draw the same legend (one legend) for the
multiple spatial figures?
I would put the legend next to the upper-most plot and
wrap the whole thing in a single
/figure
so that it would be more obvious that the same legend applied to all.