@@ -325,11 +325,15 @@ addRasterImage <- function(
325
325
addRasterLegend <- function (map , x , layer = 1 , ... ) {
326
326
stopifnot(inherits(x , " SpatRaster" ))
327
327
stopifnot(length(layer ) == 1 && layer > 0 && layer < = terra :: nlyr(x ))
328
-
328
+
329
+ # # might as well do this here and only once. Subsetting would otherwise have been necessary in
330
+ # # color_info <- base::subset(color_info, value %in% terra::values(x))
331
+ x <- x [[layer ]]
332
+
329
333
# Retrieve the color table from the layer. If one doesn't exist, that means
330
334
# the raster was colored some other way, like using colorFactor or something,
331
335
# and the regular addLegend() is designed for those cases.
332
- ct <- terra :: coltab(x )[[layer ]]
336
+ ct <- terra :: coltab(x )[[1 ]]
333
337
if (is.null(ct )) {
334
338
stop(" addRasterLegend() can only be used on layers with color tables (see ?terra::coltab). Otherwise, use addLegend()." )
335
339
}
@@ -341,10 +345,17 @@ addRasterLegend <- function(map, x, layer = 1, ...) {
341
345
color = grDevices :: rgb(ct $ red / 255 , ct $ green / 255 , ct $ blue / 255 , ct $ alpha / 255 )
342
346
)
343
347
348
+ lvls <- terra :: levels(x )[[1 ]]
349
+
344
350
# Drop values that aren't part of the layer
345
- color_info <- base :: subset(color_info , value %in% terra :: values(x ))
351
+ # # unlike "values", "unique" is memory-safe; it does not load all values
352
+ # # into memory if the raster is large. So instead of:
353
+
354
+ # color_info <- base::subset(color_info, value %in% terra::values(x))
346
355
347
- lvls <- terra :: levels(x )[[layer ]]
356
+ # # remove the levels to get the raw cell values
357
+ levels(x ) <- NULL
358
+ color_info <- base :: subset(color_info , value %in% terra :: unique(x )[[1 ]])
348
359
349
360
res <- if (is.data.frame(lvls )) {
350
361
# Use the labels from levels(x), and look up the matching colors in the
0 commit comments