2
votes

I can't get the leaflet addCircleMarkers function to apply data-mapped colors to the markers.

Nb. I generated fn.palette using colorRampPalette. It works fine, producing hex codes for colors from green > yellow > red when mapping the data vector x. The output vector colours looks like ("#00FF00FF" "#FFD200FF" "#7FFF00FF" "#FFFF00FF" ...).

If I set color to my vector of hex codes:

map %>%
    addCircleMarkers(lon, lat, color = colours, radius = 2, weight = 0,
                     fill = TRUE, fillOpacity = 0.5, opacity = 0.6)

it draws only black markers.

If I use the leaflet::pal function:

pal <- colorNumeric(palette = fn.palette, domain = x)
map %>% addCircleMarkers(lon, lat, color = pal(x), radius = radius, 
                         stroke = FALSE, fillOpacity = 1)

it gives

Warning message: In seq.int(0, 1, length.out = n) : first element used of 'length.out' argument

and draws only black markers.

Using color = ~pal(x) instead of color = pal(x) (as in the examples at https://rstudio.github.io/leaflet) throws

Error in UseMethod("metaData") : no applicable method for 'metaData' applied to an object of class "NULL"

I've run out of ideas.

1

1 Answers

4
votes

Here is a reproducible example of making a leaflet map in R with coloured circle markers.

library(leaflet)
library(viridisLite)

# get domain of numeric data
(domain <- range(quakes$depth))

# make palette
pal <- colorNumeric(palette = viridis(100), domain = domain)

# make map
leaflet(quakes) %>% 
  addTiles() %>% 
  addCircleMarkers(color = ~pal(depth))  

Some pointers:

1) When making the palette using colorNumeric (assuming you have numeric data you wish to map) ensure the domain argument is the possible values that can be mapped.

For colorNumeric and colorBin, this can be a simple numeric range (e.g. c(0, 100))

Here I have first calculated the range of quakes$depth.

2) Do ensure you use the syntax color = ~pal(depth) in addCircleMarkers

3) Also ensure the argument to ~pal() is the numeric variable in your data that you want your palette mapped to.