问题
I am using R shiny-dashboard to display a weather raster file. I used colorQuantile as the method to display the color. In the legend, it shows the percentage. As you can see in the following image. I want the labels in the legend show the range of the value instead for each bin. I am not sure how to do that.
Here is my server.R
output$weather_map <- renderLeaflet({
rw = weatherband()
if (!is.null(rw)) {
pal_w = colorQuantile('RdYlGn', values(rw), na.color = 'transparent', n = 7)
leaflet() %>%
addTiles() %>%
addRasterImage(rw, colors = pal_w, opacity = 0.5) %>%
addLegend(position = 'topright', pal = pal_w, value = raster::values(rw), opacity = 1)
}
})
Note: rw is the raster image.
Thank you in advance!!
回答1:
When I need want to adjust the labels in leaflet
I fall back to using the arguments colors
and labels
instead of pal
and values
. The upside is you can customize the downside is a few more lines of code.
Since I don't have access to rw
I'm grabbing my favorite map example:
library(sf)
nc <- st_read(system.file("shape/nc.shp", package="sf"))
Then the leaflet
alternative pattern for customizing the legend labels:
library(leaflet)
qpal <- colorQuantile("RdYlBu", nc$AREA, n = 5)
# the extra code building off the existing pal
qpal_colors <- unique(qpal(sort(nc$AREA))) # hex codes
qpal_labs <- quantile(nc$AREA, seq(0, 1, .2)) # depends on n from pal
qpal_labs <- paste(lag(qpal_labs), qpal_labs, sep = " - ")[-1] # first lag is NA
map %>%
addPolygons(stroke = FALSE, smoothFactor = 0.2, fillOpacity = 1,
color = ~qpal(AREA)
) %>%
addLegend(colors = qpal_colors, labels = qpal_labs, opacity = 1)
来源:https://stackoverflow.com/questions/56241152/addlegend-display-value-range-instead-of-percentage-when-using-colorquantile