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:
first I load the required packages
library(rgdal)
library(raster)
library(kableExtra)
library(rasterVis)
library(leaflet)
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"))
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 |
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)
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)