Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reverse colors in colorNumeric()

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?

like image 823
Pierre Dudek Avatar asked Jul 06 '16 16:07

Pierre Dudek


3 Answers

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

like image 131
Alex Avatar answered Nov 04 '22 10:11

Alex


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)
like image 24
Stefan F Avatar answered Nov 04 '22 08:11

Stefan F


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)
like image 28
TimSalabim Avatar answered Nov 04 '22 10:11

TimSalabim