10

I am trying to reverse the colors of a choropleth map. I am using the leaflet package and the colorNumeric() function, here is the code that generates the palette function:

pal <- colorNumeric(palette = "YlGnBu", domain = foo$p)

I would like to do something like that:

pal <- colorNumeric(palette = "YlGnBu", domain = foo$p, trans='reverse')

Does anyone knows how to do this?

csgillespie
  • 59,189
  • 14
  • 150
  • 185
Pierre Dudek
  • 252
  • 4
  • 11

3 Answers3

10

Without an example I cannot tell if it works with your code but try this:

library(RColorBrewer)
palette <- brewer.pal(5, "YlGnBu")
previewColors(colorNumeric(palette = palette, domain = 1:5), values = 1:5)

enter image description here

And the reverse:

palette_rev <- rev(brewer.pal(5, "YlGnBu"))
previewColors(colorNumeric(palette = palette_rev ,domain = 1:5), values = 1:5)

enter image description here

Alex
  • 4,925
  • 2
  • 32
  • 48
9

At least in leaflet 1.1.0+ colorNumeric has an optional "reverse" argument, so you can just do:

pal <- colorNumeric(palette = "YlGnBu", domain = foo$p, reverse = TRUE)
Stefan F
  • 2,573
  • 1
  • 17
  • 19
1

As suggested by @Alex here's an example using rev with some actual data:

library(leaflet)
library(mapview)
library(RColorBrewer)

clrs <- rev(brewer.pal(9, "YlGnBu"))

pal <- colorNumeric(palette = clrs, domain = poppendorf[[5]][])

m <- leaflet() %>% addTiles() 

m %>% 
  addRasterImage(x = poppendorf[[5]], color = pal)
TimSalabim
  • 5,604
  • 1
  • 25
  • 36
  • No offence intended! You must have provided your answer while I was still trying and typing my answer... I've edited mine to acknowledge yours. – TimSalabim Jul 06 '16 at 17:20