I want to have leaflet color palette centered to zero (with Red-white-green diverging). I have tried what has been told in this post. When I tried this manual creation of colors, I got the red green divergence but couldn't able to center it to zero.
My Code
regions@data <- data.frame(region <- c("APAC (excl. China)", "Africa",
"Americas", "Europe", "Greater China", "Middle East"),
change_targeted <- c(36,-21,25,4,173,34))
color = "#666"
weight = 0.5
opacity = 1
fillOpacity = 1
dashArray = ""
hl_color = "black"
hl_weight = 1
hl_dashArray = ""
library(RColorBrewer)
nHalf = nrow(regions@data)/2
Min = min(regions@data[,"change_targeted"])
Max = max(regions@data[,"change_targeted"])
Thresh = 0
## Make vector of colors for values below threshold
rc1 = colorRampPalette(colors = c("red", "white"), space="Lab")(nHalf)
## Make vector of colors for values above threshold
rc2 = colorRampPalette(colors = c("white", "green"), space="Lab")(nHalf)
rampcols = c(rc1, rc2)
## In your example, this line sets the color for values between 49 and 51.
rampcols[c(nHalf, nHalf+1)] = rgb(t(col2rgb("white")), maxColorValue=256)
rb1 = seq(Min, Thresh, length.out=nHalf+1)
rb2 = seq(Thresh, Max, length.out=nHalf+1)[-1]
rampbreaks = c(rb1, rb2)
pal <- colorNumeric(
palette = rampcols, #"Blues", #YlGnBu,YlOrRd
domain = regions@data$change_targeted)
leaflet(regions, options = leafletOptions(zoomControl = FALSE,
attributionControl=FALSE)) %>%
addPolygons(color = color,
weight = weight, #smoothFactor = 0.5,
opacity = opacity, fillOpacity = fillOpacity,
dashArray = dashArray,
fillColor = ~pal(change_targeted),
highlightOptions = highlightOptions(color = hl_color,
weight = hl_weight,
dashArray = hl_dashArray,
bringToFront = TRUE),
label =
~as.character(paste0(region,"",round(change_targeted,1),"%")),
labelOptions = labelOptions(noHide = T, textOnly = F,
direction = "left",
textsize = "12px")) %>%
setView(35, 36, 0.5) %>%
addLegend("bottomright", pal = pal, values = ~change_targeted,
title = NULL,
labFormat = labelFormat(suffix = "%"), opacity=1)
My Map chart
I would ideally want only Africa to have red color and rest of the regions with white to green palette