23

Is there anyway to change the color of leaflet marker base on the value of some variable. In the following map, for example, I wish to assign marker color based on mag variable:

library(leaflet)

data(quakes)

# Show first 20 rows from the `quakes` dataset
leaflet(data = quakes[1:20,]) %>% addTiles() %>%
  addMarkers(~long, ~lat, popup = ~as.character(mag))
1
  • I wonder if Leaflet.awesome-markers plugin v2.0 is available for R?
    – M.Qasim
    Commented Oct 5, 2015 at 3:24

5 Answers 5

28

I often use the circle markers because you can change both the size and color based on other variables. For example, I have created a binned variable from a continuous using the following code:

# first cut the continuous variable into bins
# these bins are now factors
last$BeatHomeLvl <- cut(last$BeatHome, 
                        c(0,.5,1,2,3,5,100), include.lowest = T,
                        labels = c('<.5x', '.5-1x', '1-2x', '2-3x', '3-5x','5x+'))

# then assign a palette to this using colorFactor
# in this case it goes from red for the smaller values to yellow and green
# standard stoplight for bad, good, and best
beatCol <- colorFactor(palette = 'RdYlGn', last$BeatHomeLvl)

When you plot it, I use the code for circle markers. The radius/area of the circle is based on the actual value of the factor and then color is assigned according to the bins.

m1 <- leaflet() %>%
  addTiles() %>%
  addProviderTiles(providers$OpenStreetMap, group = 'Open SM')  %>%
  addProviderTiles(providers$Stamen.Toner, group = 'Toner')  %>%
  addProviderTiles(providers$Esri.NatGeoWorldMap, group = 'NG World') %>%
  setView(lng = -72, lat = 41, zoom = 8) %>%

      addCircleMarkers(data = Jun, lat = ~Lat, lng = ~Lon,
                       color = ~beatCol(BeatHomeLvl), popup = Jun$Popup,
                       radius = ~sqrt(BeatHome*50), group = 'Home - Jun') %>%

At the end of your code add a legend. I added some formatting.

  addLegend('bottomright', pal = beatCol, values = last$BeatHomeLvl,
            title = 'Compare Home<br>Quote Count to<br>3Mos State Avg',
            opacity = 1)

This gives you color-coded and sized circles based on a variable and a nice legend.

enter image description here

3
  • where did you get last$BeatTotalLvl?
    – user34018
    Commented Oct 30, 2018 at 19:56
  • Don't know why your answer isn't the most upvoted. It's simpler and clearer than other answers Commented Jan 9, 2020 at 15:01
  • last$BeatTotalLv is a field in the data frame last; it was created by converting a continuous variable which was the ratio to the average. Commented Jan 20, 2020 at 18:08
22

As far as I know, you need to assign an image file to one level of icon. For instance, if you have three levels in magnitude in the earthquake data, you need to create an icon list with three image paths. Then, you can have three different colors in markers. At least, the following example is getting closer to what you want. I edited a png file and created three png files. You need to specify the paths of the file when you make an icon list.

library(dplyr)
library(leaflet)

mutate(quakes, group = cut(mag, breaks = c(0, 5, 6, Inf), labels = c("blue", "green", "orange"))) -> mydf

### I edit this png file and created my own marker.
### https://raw.githubusercontent.com/lvoogdt/Leaflet.awesome-markers/master/dist/images/markers-soft.png
quakeIcons <- iconList(blue = makeIcon("/Users/jazzurro/Documents/Stack Overflow/blue.png", iconWidth = 24, iconHeight =32),
                       green = makeIcon("/Users/jazzurro/Documents/Stack Overflow/green.png", iconWidth = 24, iconHeight =32),
                       orange = makeIcon("/Users/jazzurro/Documents/Stack Overflow/orange.png", iconWidth = 24, iconHeight =32))


leaflet(data = mydf[1:100,]) %>% 
addTiles() %>%
addMarkers(icon = ~quakeIcons[group])

enter image description here

3
  • Thanks for the answer. I want to customized the color of markers not the circles... github.com/lvoogdt/Leaflet.awesome-markers
    – M.Qasim
    Commented Oct 5, 2015 at 3:40
  • 1
    @M.Qasim I see. I know how one can assign different markers to different levels of a variable. But I do not know how you can change the colors of icons. As far as I know, one assigns an icon image (png file) to one level. It seems to me that you need to modify colors of png files before you use them in leaflet.
    – jazzurro
    Commented Oct 5, 2015 at 5:25
  • 2
    @M.Qasim I updated my answer. I think we need to basically create image files of markers by ourselves if we want to assign different colors to makers. Please have a look. I hope this will let you move forward.
    – jazzurro
    Commented Oct 5, 2015 at 11:05
15

This one worked for me:

Source: https://github.com/bhaskarvk/leaflet/blob/master/inst/examples/awesomeMarkers.R

library(leaflet)

icon.glyphicon <- makeAwesomeIcon(icon= 'flag', markerColor = 'blue', iconColor = 'black')
icon.fa <- makeAwesomeIcon(icon = 'flag', markerColor = 'red', library='fa', iconColor = 'black')
icon.ion <- makeAwesomeIcon(icon = 'home', markerColor = 'green', library='ion')

# Marker + Label
leaflet() %>% addTiles() %>%
  addAwesomeMarkers(
    lng=-118.456554, lat=34.078039,
    label='This is a label',
    icon = icon.glyphicon)

leaflet() %>% addTiles() %>%
  addAwesomeMarkers(
    lng=-118.456554, lat=34.078039,
    label='This is a label',
    icon = icon.fa)

leaflet() %>% addTiles() %>%
  addAwesomeMarkers(
    lng=-118.456554, lat=34.078039,
    label='This is a label',
    icon = icon.ion)

# Marker + Static Label using custom label options
leaflet() %>% addTiles() %>%
  addAwesomeMarkers(
    lng=-118.456554, lat=34.078039,
    label='This is a static label',
    labelOptions = labelOptions(noHide = T),
    icon = icon.fa)
3
  • Glad to see you found an example. I wonder which version of the leaflet package you got on your machine. I cannot run the code above since addAwesomeMarkers() do not exist in my version.
    – jazzurro
    Commented Oct 5, 2015 at 22:32
  • 1
    Leaflet version 1.0.1.9000. You may need to delete existing directory of leaflet in your library, as installing update on the top of existing package did not work for me in the first place...
    – M.Qasim
    Commented Oct 8, 2015 at 9:04
  • 1
    please install the following to get addAwesomeMarkers(). devtools::install_github('bhaskarvk/leaflet')
    – M.Qasim
    Commented Oct 8, 2015 at 11:09
5

Why not use vector markers based on svg (here is one example implementation - https://github.com/hiasinho/Leaflet.vector-markers) that you can apply any fill color you want to? Instead of having to create a large amount of static image files. Some code involved, yes, but a lot more flexible.

2

L.Marker uses images (one for the marker, one for the shadow) so that's not possible. You can however use your own images, there's a good write up on the topic among the tutorials on the Leaflet site:

http://leafletjs.com/examples/custom-icons.html

Not the answer you're looking for? Browse other questions tagged or ask your own question.