简体   繁体   中英

Leaflet: Custom bin legend for raster

I've been playing around with the leaflet package and can't create a proper legend for a raster.

The problem is as follows: I've created an informative map with this code:

raster file: https://drive.google.com/open?id=0B7mw858dxh5MODZqSHNHbFR3clU

library(raster)
library(leaflet)
r <- raster('raster.tif')
colores <- c('red', 'green', 'blue', 'chocolate', 'deeppink', 'grey')
at <- seq(0, 4800, 800)
cb <- colorBin(palette = colores, bins = length(at), domain = at)

leaflet() %>% 
    setView(-67.5,-16, zoom = 7) %>%
    addRasterImage(r, colors = cb) %>%
    addLegend(pal = cb, values = at)

Variable r is a raster with precipitation data ranging from 171 to 4667 mm/year.

Output:

https://i.imgur.com/bt7Ew6O.png

I want to get a legend with 6 bins using the colors passed to the variable colores but the output shows 10 bins ignoring the ranges I passed to the at variable.

How should I achieve what I want?

You simply need to replace length(at) with at in your colorBin call

library(raster)
library(leaflet)
r <- raster('raster.tif')
colores <- c('red', 'green', 'blue', 'chocolate', 'deeppink', 'grey')
at <- seq(0, 4800, 800)
cb <- colorBin(palette = colores, bins = at, domain = at)

leaflet() %>% 
    setView(-67.5,-16, zoom = 7) %>%
    addRasterImage(r, colors = cb) %>%
    addLegend(pal = cb, values = at)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM