@@ -341,19 +341,25 @@ addRasterLegend <- function(map, x, layer = 1, ...) {
341
341
color = grDevices :: rgb(ct $ red / 255 , ct $ green / 255 , ct $ blue / 255 , ct $ alpha / 255 )
342
342
)
343
343
344
+ # Drop values that aren't part of the layer
345
+ color_info <- base :: subset(color_info , value %in% terra :: values(x ))
346
+
344
347
lvls <- terra :: levels(x )[[layer ]]
345
348
346
349
res <- if (is.data.frame(lvls )) {
347
350
# Use the labels from levels(x), and look up the matching colors in the
348
351
# color table
352
+
353
+ # The levels data frame can have varying colnames, just normalize them
349
354
colnames(lvls ) <- c(" value" , " label" )
350
355
base :: merge(color_info , lvls , by.x = " value" , by.y = 1 )
351
356
} else {
357
+ # No level labels provided; use the values as labels
352
358
cbind(color_info , label = color_info $ value )
353
359
}
354
360
355
- # Drop values that aren't part of the layer
356
- res <- res [ res [[ " value " ]] %in% terra :: values( x ),]
361
+ # At this point, res is a data frame with `value`, `color`, and `label` cols,
362
+ # and values/colors not present in the raster layer have been dropped
357
363
358
364
addLegend(map , colors = res [[" color" ]], labels = res [[" label" ]], ... )
359
365
}
0 commit comments