Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Leaflet for R: How to customize the coloring of clusters?

Tags:

r

leaflet

shiny

How do I customize the coloring of the addMarkers function in the leaflet package for R?

The default coloring for clusters is:

  • 1-10 Green
  • 11-100 Yellow
  • 100+ Red

I'd like to change the ranges and colors to something like:

  • 1-100 Red
  • 101-1000 Yellow
  • 1000+ Green

JS Leaflet has this capability: https://github.com/Leaflet/Leaflet.markercluster#customising-the-clustered-markers

Is this possible through a markerClusterOptions parameter in the R package?

leaflet(quakes) %>% addTiles() %>% addMarkers(
  clusterOptions = markerClusterOptions()
)
like image 641
Tim_K Avatar asked Nov 08 '15 22:11

Tim_K


1 Answers

You can use the iconCreateFunction in the markerClusterOptions to create your own custom icon function to display the cluster markers.

In your example, you can maybe just modify the default marker function (found here) and just modify the if/else loops setting the CSS class of the markers. The default CSS that colors the markers can be found here. You can create your own classes if you want more customisation.

Here's a code example (large is red coloring, medium is yellow, and small is green so I just switched the default code around to match your conditions):

library(leaflet)
leaflet(quakes) %>% addTiles() %>% addMarkers(
  clusterOptions = markerClusterOptions(iconCreateFunction=JS("function (cluster) {    
    var childCount = cluster.getChildCount(); 
    var c = ' marker-cluster-';  
    if (childCount < 100) {  
      c += 'large';  
    } else if (childCount < 1000) {  
      c += 'medium';  
    } else { 
      c += 'small';  
    }    
    return new L.DivIcon({ html: '<div><span>' + childCount + '</span></div>', className: 'marker-cluster' + c, iconSize: new L.Point(40, 40) });

  }"))
)
like image 93
NicE Avatar answered Nov 16 '22 03:11

NicE