0

I am trying to create a custom palette with 2 colors(Red and Green) and custom breakpoints for my leaflet map. Currently I am using a single reds color palette.Mymap Which I have generated using colornumeric as

pal2 <- colorNumeric(palette = "Reds", domain=NULL)

I have used it in my leaflet as

leafletProxy("map", data = selecteddata()) %>% #, data = temp2.df ------ took it out/ selecteddata()
  addPolygons(data = temp2.df ,fillColor = ~pal2(selecteddata()),
              highlightOptions = highlightOptions(color = "orange", weight = 2), 
              color = "#BDBDC3",
              fillOpacity = 0.8,
              weight = 1,
              label = ~NAME                
  )

What I am looking for is to color the map in both colors green and red instead with breaks at Green - +10%, +20%, +35%, +50%, +inf Reds - -10%, -20%, -35%, -50%, -inf

Desired color palette

How do I achieve this?

PS - Also I want to drop the uncolored region of the map in the final display to make it look like 2nd image

Community
  • 1
  • 1

1 Answers1

0

Palettes are tricky when you want complicated colours / breakpoints. An alternative is to add a colour column to your data, and calculate the appropriate RGB values yourself. Its takes few extra lines of code, but you get better control:

enter image description here

Below is a minimal example, using the desired palette:

library(leaflet)
library(maps)

#Load a map of the US from the 'map' package
shp_map = map("state", fill = TRUE, plot = FALSE)

#Add a made up percentage
shp_map$percentage <- sample(seq(from = -100, to = 50), length(shp_map$names))

#Define the breaks and associated RGB value
vec_breaks <- c(     -100,       -50,       -35,       -20,       -10,         0,        10,        20,        35,        55)
vec_rgb    <- c("#b51224", "#d93e22", "#f5783f", "#ffb15a", "#ffe08d", "#dae88e", "#a1cd6a", "#67ac62", "#15854c", "#005c37") 

#Add a colour column, and put in the appropriate RGB value
for (i in 1:length(shp_map$percentage)) {
    shp_map$colour[i] <- vec_rgb[min(which(vec_breaks > shp_map$percentage[i])) - 1]
}

#Draw map
leaflet(data = shp_map) %>% 
    addPolygons(fillColor = shp_map$colour, stroke = TRUE, fillOpacity = 0.8, color = "black", opacity = 1, weight = 1)
Ash
  • 1,463
  • 1
  • 4
  • 7