Change leaflet marker fill color by group

Advertisements

In the example below, I have cities located on a leaflet map. I would like the fill color to be yellow for cities in Virginia and green for cities in North Carolina. How can I set the fill colors of circle markers by group on a leaflet map?

Example

# Import needed libraries
library(tidyverse)
library(leaflet)
library(sf)

# Create example dataset
aa <- data.frame(
  state = c('Virginia','Virginia','North Carolina', 'North Carolina'),
  city = c('Richmond','Charlottesville', 'Raleigh', 'Charlotte'),
  lat = c(37.53,38.01,35.78,35.22),
  lon = c(-77.44,-78.47,-78.63,-80.84)) %>%
  st_as_sf(coords = c('lon', 'lat'), crs = 4269) %>%
  mutate(lat = st_coordinates(.)[, 2],
         lon = st_coordinates(.)[, 1])

# Make map (this fills all points red)
aa %>%
  leaflet(options = leafletOptions(attributionControl = F,
                                 zoomControl = F)) %>%
  addTiles() %>%
  addProviderTiles("Esri.WorldImagery") %>%
  setView(-78.47,
          36.53,
          zoom = 7) %>%
  addCircleMarkers(lng = ~lon,
                   lat = ~lat,
                   fillColor = 'red',
                   fillOpacity = 1,
                   color = 'black',
                   stroke = TRUE,
                   weight = 2,
                   radius = 5)

>Solution :

In case of a discrete variable you can create a color palette using leaflet::colorFactor. This color palette could then be used to assign the fillColor based on your state column:

# Import needed libraries
library(tidyverse)
library(leaflet)
library(sf)

pal <- leaflet::colorFactor(c("red", "blue"), domain = unique(aa$state))

leaflet(options = leafletOptions(
  attributionControl = F,
  zoomControl = F
)) %>%
  addTiles() %>%
  addProviderTiles("Esri.WorldImagery") %>%
  setView(-78.47,
    36.53,
    zoom = 7
  ) %>%
  addCircleMarkers(
    lng = aa$lon,
    lat = aa$lat,
    label = aa$city,
    fillColor = pal(aa$state),
    fillOpacity = 1,
    color = "black",
    stroke = TRUE,
    weight = 2,
    radius = 5
  )

Leave a ReplyCancel reply