Derek Corcoran
Derek Corcoran

Reputation: 4092

Failed to add a categorical legend in leaflet in R using addLegend(labels)

All the files for this question are in the following git:

I am trying to plot a categorical map in leaflet with a categorical legend showing a character vector as labels:

Load the packages

first I load the required packages

library(rgdal)
library(raster)
library(kableExtra)
library(rasterVis)
library(leaflet)

Then I load the required datasets

Codes <- readRDS("Codes.rds")
LandCover <- readRDS("LandCover.rds")

if we look at the landcover raster it is a categorical raster that I made with ratify from the raster package

LandCover

## class      : RasterLayer 
## dimensions : 832, 680, 565760  (nrow, ncol, ncell)
## resolution : 30.00002, 29.99993  (x, y)
## extent     : 288800.8, 309200.8, 6367272, 6392231  (xmin, xmax, ymin, ymax)
## crs        : +proj=utm +zone=19 +south +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0 
## source     : memory
## names      : LC_CHILE_2014_b 
## values     : 150, 932  (min, max)
## attributes :
##         ID          names IDs
##  from: 150       Cultivos 150
##   to : 932 Suelos rocosos 932

I want to have the name attribute as the legend

which works using the levelplot function from the rasterVis package:

rasterVis::levelplot(LandCover)

The data is also repited in the Codes data.frame if it works

kable(Codes, caption = "Tabla de atributos del mapa") %>%
  kable_styling(bootstrap_options = c("striped", "hover"))
Tabla de atributos del mapa Code Selected 150 Cultivos 212 Nativo de Hoja Ancha 251 Plantaciones de bosque introducido 330 Pastizales 450 Matorrales 510 Humedales 640 Cuerpo de agua 800 Superficies impermeables 920 Suelos arenosos 932 Suelos rocosos

Two tests that didn’t work

Test 1

pal <- colorFactor(rainbow(10), values(LandCover),
                    na.color = "transparent")

leaflet() %>% addTiles()  %>%  addRasterImage(LandCover, colors = pal, opacity = 0.8) %>%  addLegend(pal = pal, values = values(LandCover),title = "Land Cover", labels = Codes$Selected)

enter image description here

Test 2

In this second one I thought that adding the labels attribute to the addLegend function would do the trick, but it does not work

pal <- colorFactor(rainbow(10), values(LandCover),
                    na.color = "transparent")

leaflet() %>% addTiles()  %>%  addRasterImage(LandCover, colors = pal, opacity = 0.8) %>%  addLegend(pal = pal, values = values(LandCover),title = "Land Cover", labels = Codes$Selected)

enter image description here

Upvotes: 3

Views: 2253

Answers (1)

lbusett
lbusett

Reputation: 5932

You can achieve that by exploiting the labFormat argument of addLegend. The trick is using a transform function within labFormat to re-map the IDs of the RAT to the corresponding labels.

Something like this seems to work:

library(rgdal)
library(raster)
library(leaflet)

Codes <- readRDS("C:\\Users\\LB_laptop\\Downloads\\Codes.rds")
LandCover <- readRDS("C:\\Users\\LB_laptop\\Downloads\\LandCover.rds")

pal <- colorFactor(rainbow(10), values(LandCover),
                    na.color = "transparent")

leaflet() %>% addTiles()  %>% 
  addRasterImage(LandCover, colors = pal, opacity = 0.8) %>%
  addLegend(pal = pal, 
            values = values(LandCover),
            title = "Land Cover",
            labFormat  = labelFormat(
            transform = function(x) {
              levels(LandCover)[[1]]$names[which(levels(LandCover)[[1]]$ID == x)]
            }))

Created on 2019-11-30 by the reprex package (v0.3.0)

Upvotes: 3

Related Questions